import 'dart:convert'; import 'dart:io'; import 'package:dio/dio.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter_easyloading/flutter_easyloading.dart'; import 'package:flutter_smart_dialog/flutter_smart_dialog.dart'; import 'package:flutter_svg/flutter_svg.dart'; import 'package:huixiang/community/community_page.dart'; import 'package:huixiang/generated/l10n.dart'; import 'package:huixiang/home/home_page.dart'; import 'package:huixiang/main.dart'; import 'package:huixiang/mine/mine_page.dart'; import 'package:huixiang/retrofit/data/app_update.dart'; import 'package:huixiang/retrofit/data/base_data.dart'; import 'package:huixiang/retrofit/data/examine_instance.dart'; import 'package:huixiang/retrofit/data/user_info.dart'; import 'package:huixiang/retrofit/retrofit_api.dart'; import 'package:huixiang/union/union_page.dart'; import 'package:flutter_screenutil/flutter_screenutil.dart'; import 'package:huixiang/utils/bridge.dart'; import 'package:huixiang/utils/event_type.dart'; import 'package:huixiang/utils/flutter_utils.dart'; import 'package:huixiang/utils/font_weight.dart'; import 'package:huixiang/utils/native_event_handler.dart'; import 'package:huixiang/view_widget/update_dialog.dart'; import 'package:huixiang/vip/vip_page.dart'; import 'package:package_info/package_info.dart'; import 'package:permission_handler/permission_handler.dart'; import 'package:shared_preferences/shared_preferences.dart'; import 'package:sharesdk_plugin/sharesdk_interface.dart'; import 'package:sharesdk_plugin/sharesdk_register.dart'; import 'package:tpns_flutter_plugin/android/xg_android_api.dart'; import 'package:tpns_flutter_plugin/tpns_flutter_plugin.dart'; import 'package:umeng_common_sdk/umeng_common_sdk.dart'; import 'community/order_page.dart'; class MainPage extends StatefulWidget { final Map arguments; MainPage({this.arguments}); @override State createState() { return _MainPage(); } } class _MainPage extends State with WidgetsBindingObserver { List _widgetOptions; List icons; final GlobalKey homePageKey = GlobalKey(); final GlobalKey minePageKey = GlobalKey(); final GlobalKey unionPageKey = GlobalKey(); final GlobalKey vipPageKey = GlobalKey(); // List iconn; ApiService apiService; int lastTime = DateTime.now().millisecondsSinceEpoch; String _platformVersion = 'Unknown'; @override void dispose() { super.dispose(); WidgetsBinding.instance.removeObserver(this); } @override void didChangeAppLifecycleState(AppLifecycleState state) { print("-didChangeAppLifecycleState-" + state.toString()); switch (state) { case AppLifecycleState.inactive: // 处于这种状态的应用程序应该假设它们可能在任何时候暂停。 break; case AppLifecycleState.resumed: //从后台切换前台,界面可见 pushRoute(); if (DateTime.now().millisecondsSinceEpoch - lastTime > 420000) //处于后台**分钟后刷新应用 // Navigator.of(context).popAndPushNamed('/router/start_page'); setState((){}); break; case AppLifecycleState.paused: // 界面不可见,后台 lastTime = DateTime.now().millisecondsSinceEpoch; break; case AppLifecycleState.detached: // APP结束时调用 break; } } @override void initState() { super.initState(); pageController = PageController( initialPage: widget.arguments != null && widget.arguments["index"] != null ? widget.arguments["index"] : 0); if (widget.arguments != null && widget.arguments["index"] != null) clickIndex = widget.arguments["index"]; WidgetsBinding.instance.addObserver(this); EasyLoading.instance ..indicatorType = EasyLoadingIndicatorType.circle // ..indicatorType = EasyLoadingIndicatorType.wave // ..indicatorType = EasyLoadingIndicatorType.threeBounce ..loadingStyle = EasyLoadingStyle.dark ..indicatorSize = 35.0 ..backgroundColor = Colors.white ..progressColor = Colors.green ..progressWidth = 3.0 ..userInteractions = false ..dismissOnTap = false; initSdk(); UmengCommonSdk.initCommon('6491509087568a379b5a1345', '6491509087568a379b5a1345', 'Umeng'); UmengCommonSdk.setPageCollectionModeManual(); initPlatformState(); pushRoute(); String invite = ""; var interviewCouponList; var firstLoginCouponList; if (widget.arguments != null && (widget.arguments["invite"] ?? "") != "" && widget.arguments["interviewCouponList"] != null) { invite = widget.arguments["invite"]; interviewCouponList = widget.arguments["interviewCouponList"]; } if (widget.arguments != null && widget.arguments["firstLoginCouponList"] != null) { firstLoginCouponList = widget.arguments["firstLoginCouponList"]; } _widgetOptions = [ // BrandPage(), HomePage( homePageKey, (index, jpIndex) { if (index == 1) { if (unionPageKey?.currentState != null) { UnionPageState state = unionPageKey.currentState; state.jumpIndex(jpIndex); } else _widgetOptions[1] = UnionPage(unionPageKey, jpIndex); } setState(() { pageController.jumpToPage(index); }); }, invite: invite, interviewCouponList: interviewCouponList, firstLoginCouponList: firstLoginCouponList, ), // MainHomePage(), UnionPage(unionPageKey, 0), VipPage(vipPageKey), Platform.isAndroid ? (ExamineInstance.instance.isExamine ? OrderPage() : CommunityPage()) : CommunityPage(), // CommunityPage(), MinePage(minePageKey), ]; icons = [ "assets/svg/jingbi.svg", "assets/svg/lianmeng.svg", "assets/svg/huixiang_vip.svg", "assets/svg/shequn.svg", "assets/svg/wode.svg", ]; // iconn = [ // "assets/image/icon_brand_n.webp", // "assets/image/icon_bi_n.webp", // "assets/image/icon_meng_n.webp", // "assets/image/icon_wo_n.webp", // ]; eventBus.on().listen((event) { if (event.type < 3) { setState(() {}); } }); queryUserInfo(); ///App自动更新 appAutoUpdate(); } final XgFlutterPlugin xgFlutterPlugin = XgFlutterPlugin(); Future initPlatformState() async { String platformVersion; try { platformVersion = (await UmengCommonSdk.platformVersion); } on PlatformException { platformVersion = 'Failed to get platform version.'; } if (!mounted) return; setState(() { _platformVersion = platformVersion; }); } initSdk() async { xgFlutterPlugin.stopXg(); ///ios 调用startXg前需要调用此方法 xgFlutterPlugin.configureClusterDomainName("tpns.sh.tencent.com"); xgFlutterPlugin.setEnableDebug(true); ///此处配置为iOS的appID信息,Android信息在build.gradle文件中 xgFlutterPlugin.startXg("1680005688", "IYIB3R2XRE22"); if (Platform.isAndroid) { XgAndroidApi androidApi = xgFlutterPlugin.getXgAndroidApi(); //小米 androidApi.setMiPushAppId(appId: "2882303761520050452"); androidApi.setMiPushAppKey(appKey: "5582005091452"); androidApi.enableOtherPush(); androidApi.regPush(); } ShareSDKRegister shareSDKRegister = ShareSDKRegister(); shareSDKRegister.setupWechat( "wx3b269e795ed23e5f", "64020361b8ec4c99936c0e3999a9f249", "https://hx.lotus-wallet.com/app/", ); shareSDKRegister.setupFacebook( "523308712059457", "d3a1b6377100871799d8973fbe84794a", "海峡姐妹", ); SharesdkPlugin.regist(shareSDKRegister); // LocationFlutterPlugin myLocPlugin = LocationFlutterPlugin(); // // 设置是否隐私政策 // myLocPlugin.setAgreePrivacy(true); // BMFMapSDK.setAgreePrivacy(true); // if (Platform.isIOS) { // myLocPlugin.authAK("ylW2QPlsbERkho7jOgU4GQSeawmdUIoR"); // BMFMapSDK.setApiKeyAndCoordType( // 'ylW2QPlsbERkho7jOgU4GQSeawmdUIoR', // BMF_COORD_TYPE.BD09LL, // ); // } else if (Platform.isAndroid) { // BMFMapSDK.setCoordType(BMF_COORD_TYPE.BD09LL); // } if (Platform.isAndroid) { xgFlutterPlugin.getXgAndroidApi().addNativeEventHandler( MyNativeEventHandler( (String title, String message, String customContent, int type) { print("xgPushClickAction2: $customContent"); SharedPreferences.getInstance().then((value) { value.setString("pushData", customContent); }); }, ), ); } /// @typed: ARTICLE(1)文章 ACTIVITY(2)活动 SHOP(3)店铺 CREDIT_GOODS(4)积分商品 ORDER(5)订单 TREND(6)动态 MEMBER(7)用户 WALLET(8)平台余额/钱包 WELFARE(9)福利中心 COUPON(12)优惠券列表 CATE_BEAN(13)我的印章 xgFlutterPlugin.addEventHandler(xgPushClickAction: (event) async { print("xgPushClickAction1: $event"); if (event["actionType"] == 2) return event; if (Platform.isAndroid ? (event["actionType"] == 0) : (event["xg"]["msgtype"] == 1) && event[Platform.isAndroid ? "customMessage" : "custom"] != null) { SharedPreferences.getInstance().then((value) { value.setString("pushData", event[Platform.isAndroid ? "customMessage" : "custom"]); }); if (ModalRoute.of(context).isActive && ModalRoute.of(context).isCurrent) { pushRoute(); } else { Navigator.of(context) .pushNamedAndRemoveUntil('/router/main_page', (route) => false); } } return event; }, onReceiveNotificationResponse: (event) async { try { if (jsonDecode(event["customMessage"])["typed"] == 6) { // HomePageState state = homePageKey.currentState; // state.queryMsgStats(); MinePageState state = minePageKey.currentState; state.queryMsgStats(); } } catch (ex) {} print("onReceiveNotificationResponse: ${event.toString()}"); return event; }, onReceiveMessage: (event) async { print("onReceiveMessage: ${event.toString()}"); return event; }, onRegisteredDone: (event) async { print("onRegisteredDone: ${event.toString()}"); return event; }, xgPushDidBindWithIdentifier: (event) async { print("xgPushDidBindWithIdentifier: ${event.toString()}"); return event; }); } pushRoute() async { SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); if (sharedPreferences.getString("token") == null || sharedPreferences.getString("token") == "") return; String startIntent; if (Platform.isAndroid) startIntent = await Bridge.getStartIntent(); print("intent:$startIntent"); String pushData = ""; if (startIntent != null && startIntent != "") { pushData = startIntent; // pushData = """{"typed":1,"info":"1420304936817655808"}"""; } else { pushData = sharedPreferences.getString("pushData"); } if (pushData == null || pushData == "") return; Map pushMap = jsonDecode(pushData); if (pushMap != null) { String routeName = ""; Map params = {}; switch (pushMap["typed"].toString()) { case "1": case "ARTICLE": routeName = "/router/web_page"; params["articleId"] = pushMap["info"]; break; case "2": case "ACTIVITY": routeName = "/router/web_page"; params["activityId"] = pushMap["info"]; break; case "3": case "SHOP": routeName = "/router/store_order"; params["id"] = pushMap["info"]; params["tenant"] = pushMap["tenant"]; params["storeName"] = pushMap["storeName"]; break; case "4": case "CREDIT_GOODS": routeName = "/router/integral_store_page"; params["goodsId"] = pushMap["info"]; break; case "5": case "ORDER": routeName = "/router/order_details"; params["id"] = pushMap["info"]; break; case "6": case "MEMBER": routeName = "/router/community_details"; params["businessId"] = pushMap["info"]; break; case "8": case "WALLET": routeName = "/router/mine_wallet"; params["id"] = pushMap["info"]; break; case "9": case "WELFARE": routeName = "/router/welfare_page"; params["id"] = pushMap["info"]; break; case "12": case "COUPON": routeName = "/router/coupon_page"; params["id"] = pushMap["info"]; break; case "13": case "CATE_BEAN": routeName = "/router/trading_card_page"; params["id"] = pushMap["info"]; break; } sharedPreferences.setString("pushData", ""); print("xgPushClickAction: routeName: $routeName"); if (routeName != "") { Navigator.of(context).pushNamed(routeName, arguments: params); } } } queryUserInfo() async { SharedPreferences sharedPreferences = await SharedPreferences.getInstance(); if (sharedPreferences.getString("token") == null || sharedPreferences.getString("token") == "") return; BaseData baseDate = await ApiService( Dio(), context: context, token: sharedPreferences.getString('token'), ).queryInfo().catchError((onError) {}); sharedPreferences.setString('user', jsonEncode(baseDate.data)); //用户登录时,注册推送的标识是手机号 String mobile = baseDate.data.phone; if (mobile != null && mobile != "") { xgFlutterPlugin.setAccount(mobile, AccountType.PHONE_NUMBER); // xgFlutterPlugin.unbindWithIdentifier(identify: mobile, bindType: XGBindType.account) xgFlutterPlugin.bindWithIdentifier( identify: mobile, bindType: XGBindType.account, ); } } requestPermission() async { if (!await Permission.storage.isGranted) { await Permission.storage.request(); } } ///app自动更新 appAutoUpdate() async { SharedPreferences value = await SharedPreferences.getInstance(); if (apiService == null) { apiService = ApiService( Dio(), context: context, token: value.getString("token"), ); } PackageInfo packageInfo = await PackageInfo.fromPlatform(); BaseData baseData = await apiService.appVersion().catchError((onError) {}); if (baseData != null && baseData.isSuccess) { // baseData.data.appLastVersion = "2.0.17"; // baseData.data.appLastVersionUp = "1.0.1"; if (AppUtils.versionCompare( packageInfo.version, baseData.data?.appLastVersion) && AppUtils.versionCompare(value.getString("appLastVersion") ?? "1.0.0", baseData.data?.appLastVersion)) { showDialog( context: context, barrierDismissible: false, builder: (BuildContext context) { return WillPopScope( child: UpdateDialog(packageInfo.version, baseData.data), onWillPop: () async { return Future.value(false); }); }, ); } else { return; } } else { SmartDialog.showToast(baseData.msg, alignment: Alignment.center); Navigator.of(context).pop(); } } PageController pageController; @override Widget build(BuildContext context) { return Scaffold( resizeToAvoidBottomInset: false, body: Container( child: PageView( controller: pageController, children: _widgetOptions, physics: NeverScrollableScrollPhysics(), onPageChanged: (index) { clickIndex = index; setState(() {}); }, ), ), extendBody: true, bottomNavigationBar: Container( alignment: Platform.isAndroid ? Alignment.center : Alignment.topCenter, decoration: BoxDecoration( color: Colors.white, boxShadow: [ BoxShadow( color: Colors.black.withAlpha(12), offset: Offset(0, 2), blurRadius: 4, spreadRadius: 0, ), ], borderRadius: BorderRadius.vertical( top: Radius.circular(4), ), ), height: 82.h, child: Row( mainAxisAlignment: MainAxisAlignment.spaceAround, crossAxisAlignment: CrossAxisAlignment.start, children: [ // bottomNavigationBigItem(S.of(context).pinpai, 0), bottomNavigationItem(S.of(context).main_menu1, 0), bottomNavigationItem(S.of(context).main_menu2, 1), // bottomNavigationItem(S.of(context).main_menu3 , 2), bottomNavigationItem(S.of(context).main_menu5, 2), bottomNavigationItem( Platform.isAndroid ? (ExamineInstance.instance.isExamine ? "订单" : S.of(context).main_menu3) : S.of(context).main_menu3, 3), bottomNavigationItem(S.of(context).main_menu4, 4), ], ), ), ); } var clickIndex = 0; Widget bottomNavigationItem(text, index) { var isSelected = index == clickIndex; return Expanded( child: InkWell( onTap: () { setState(() { clickIndex = index; // if (index == 1) { // debugDumpApp(); // } pageController.jumpToPage(clickIndex); }); }, child: Container( width: 45.w, child: Column( mainAxisAlignment: Platform.isAndroid ? MainAxisAlignment.center : MainAxisAlignment.start, crossAxisAlignment: CrossAxisAlignment.center, children: [ if (Platform.isIOS) SizedBox( height: 4.h, ), // AnimatedCrossFade( // firstChild: SvgPicture.asset( // icons[index], // width: 30, // height: 30, // fit: BoxFit.contain, // ), // // Image.asset( // // icons[index], // // width: 30, // // height: 30, // // fit: BoxFit.contain, // // ), // secondChild: Image.asset( // iconn[index], // width: 30, // height: 30, // fit: BoxFit.contain, // ), // crossFadeState: isSelected // ? CrossFadeState.showFirst // : CrossFadeState.showSecond, // duration: Duration(milliseconds: 200), // ), SvgPicture.asset( icons[index], width: 30, height: 30, color: isSelected ? Color(0xFF32A060) : Color(0xFFE6E6E6), fit: BoxFit.contain, ), Text( text, style: TextStyle( fontSize: 10, fontWeight: MyFontWeight.semi_bold, color: Color(isSelected ? 0xFF32A060 : 0xFFC6C6C6), ), ), ], ), ), ), flex: 1, ); } // Widget bottomNavigationBigItem(text, index) { // var isSelected = index == clickIndex; // return Expanded( // child: InkWell( // onTap: () { // setState(() { // clickIndex = index; // pageController.jumpToPage(clickIndex); // }); // }, // child: Container( // width: 45.w, // alignment: Alignment.center, // child: AnimatedCrossFade( // firstCurve: Curves.easeIn, // secondCurve: Curves.ease, // sizeCurve: Curves.easeInOut, // duration: Duration(milliseconds: 50), // firstChild: Container( // padding: EdgeInsets.all(4), // height: 82.h, // alignment: // Platform.isAndroid ? Alignment.center : Alignment.topCenter, // child: Image.asset( // icons[index], // width: 45, // height: 45, // fit: BoxFit.contain, // ), // ), // secondChild: Column( // mainAxisAlignment: Platform.isAndroid // ? MainAxisAlignment.center // : MainAxisAlignment.start, // crossAxisAlignment: CrossAxisAlignment.center, // children: [ // if (Platform.isIOS) // SizedBox( // height: 4.h, // ), // Image.asset( // iconn[index], // width: 30, // height: 30, // fit: BoxFit.contain, // ), // SizedBox( // height: 1.h, // ), // Text( // text, // style: TextStyle( // fontSize: 10.sp, // fontWeight: MyFontWeight.semi_bold, // color: Color(isSelected ? 0xFF4C4C4C : 0xFFA29E9E), // ), // ), // ], // ), // crossFadeState: isSelected // ? CrossFadeState.showFirst // : CrossFadeState.showSecond, // ), // ), // ), // flex: 1, // ); // } }