import 'dart:async'; import 'dart:convert' as convert; import 'dart:io'; import 'package:cached_network_image/cached_network_image.dart'; import 'package:flutter/cupertino.dart'; import 'package:flutter/foundation.dart'; import 'package:flutter/material.dart'; import 'package:flutter/services.dart'; import 'package:flutter/widgets.dart'; import 'package:moblink/moblink.dart'; import 'package:mobcommonlib/mobcommonlib.dart'; import 'package:permission_handler/permission_handler.dart'; import 'package:provider/provider.dart'; import 'package:zhiying_base_widget/dialog/global_dialog/advertising_dialog/advertising_dialog.dart'; import 'package:zhiying_base_widget/dialog/global_dialog/intellect_search_goods_dialog/intellect_create.dart'; import 'package:zhiying_base_widget/dialog/global_dialog/notification_setting_dialog/notification_setting_dialog.dart'; import 'package:zhiying_base_widget/dialog/notification_dialog/notification_dialog.dart'; import 'package:zhiying_base_widget/dialog/tip_dialog/tip_dialog.dart'; import 'package:zhiying_base_widget/models/app_config_model.dart'; import 'package:zhiying_base_widget/pages/custom_page/event/reload_event.dart'; import 'package:zhiying_base_widget/utils/contants.dart'; import 'package:zhiying_base_widget/utils/mob_push_util.dart'; import 'package:zhiying_base_widget/widgets/restart_widget/restart_widget.dart'; import 'package:zhiying_comm/models/base/base_tab_model.dart'; import 'package:zhiying_comm/util/image_util.dart'; import 'package:zhiying_comm/util/mob_util/mob_util.dart'; import 'package:sharesdk_plugin/sharesdk_plugin.dart'; import 'package:zhiying_comm/util/shared_prefe_util.dart'; import 'package:zhiying_comm/util/update/app_update_util.dart'; import 'package:zhiying_comm/zhiying_comm.dart'; import 'package:zhiying_comm/util/event_util/login_success_event.dart'; import 'package:zhiying_comm/util/event_util/event_util.dart'; import 'package:zhiying_comm/util/event_util/log_out.dart'; import 'package:flutter_alibc/flutter_alibc.dart'; import '../../models/app_config_model.dart'; class HomeCenterPage extends StatefulWidget { @override _HomeCenterPageState createState() => _HomeCenterPageState(); } class _HomeCenterPageState extends State { @override Widget build(BuildContext context) { return RestartWidget(child: HomePage()); } } class HomePage extends StatefulWidget { HomePage({Key key}) : super(key: key); @override _HomePageState createState() => _HomePageState(); } class _HomePageState extends State with WidgetsBindingObserver, TickerProviderStateMixin, AutomaticKeepAliveClientMixin { int _currentIndex = 0; List> _data = List(); static const EventChannel _eventChannel = const EventChannel('JAVA_TO_FLUTTER'); StreamSubscription streamSubscription; StreamSubscription reloadSubscription; StreamSubscription logOutSubscription; StreamSubscription loginSubscription; StreamSubscription eventChannelSubscription; @override void initState() { ///初始化一些数据 initAsync(); //如果登出则重新打开首页 streamSubscription = EventUtil.instance.on().listen((event) async { UserInfoModel user = await Provider.of(context, listen: false).getUserInfoModel(); user.token = ''; Navigator.maybePop(context); print("重启1"); Navigator.pushReplacementNamed(context, "/homePage"); }); reloadSubscription = EventUtil.instance.on().listen((event) async { print("重启2"); await BaseSettingModel.init(isGetCache: false); RestartWidget.restartApp(context); }); super.initState(); } ///初始化各种监听 initAsync() async { try { WidgetsBinding.instance.addObserver(this); // mob锁粉隐私协议提交 Moblink.uploadPrivacyPermissionStatus(1, (bool success) {}); // mob分享SDK隐私协议提交 SharesdkPlugin.uploadPrivacyPermissionStatus(1, (bool success) {}); // mob短信SDK隐私协议提交 Mobcommonlib.submitPolicyGrantResult(true, (dynamic ret, Map err) => {}); // 监听开始(传递监听到原生端,用户监听场景还原的数据回传回来) eventChannelSubscription = _eventChannel.receiveBroadcastStream().listen(_onEvent, onError: _onError); ///渲染完第一帧后调用 WidgetsBinding.instance.addPostFrameCallback((timeStamp) { int delay = ((num.tryParse(AppConfigModel.appStartDelay) ?? 0.5) * 1000).toInt(); print("延时" + AppConfigModel.appStartDelay.toString()); Timer(Duration(milliseconds: delay), () { NativeUtil.notifyInitSuccess(); //app后台杀死时候的还原 Timer(Duration(milliseconds: 1500), () { Moblink.restoreScene(_restore); }); }); }); initBaseSet(); Constants.isShowIntellectDialog = false; TaobaoAuth.initAuth(context); //弹窗 _showPolicy(); ///设置推送标识 setAlias(); // 是安卓系统,Android场景还原的实现 /*if (defaultTargetPlatform == TargetPlatform.android) { }*/ logOutSubscription = EventUtil.instance.on().listen((event) { MobPushUtil.deleteAlias(); SharedPreferencesUtil.setStringValue(Constants.isSetTag, "0"); }); MobPushUtil.addPushReceiver(); loginSubscription = EventUtil.instance.on().listen((event) async { setAlias(); }); } catch (e, s) { print(e); print(s); } } initBaseSet() { String data = BaseSettingModel.setting.tab['data']; try { List list = convert.jsonDecode(data); _data = list.map((item) { return Map.from(item); }).toList(); Logger.debug(_data); } catch (error) { Logger.error(error); } } @override void dispose() { print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Homepagedispose>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); WidgetsBinding.instance.removeObserver(this); streamSubscription.cancel(); reloadSubscription?.cancel(); logOutSubscription?.cancel(); loginSubscription?.cancel(); eventChannelSubscription?.cancel(); super.dispose(); } @override void didChangeAppLifecycleState(AppLifecycleState state) { ///智能粘贴板 IntellectCreate.checkAndCreate(state, context); super.didChangeAppLifecycleState(state); } @override Widget build(BuildContext context) { ScreenUtil.init(context, width: 750, height: 1334); Logger.debug('home_page build'); List> tabs = _data; if (tabs == null || tabs.length == 0) { return Scaffold(); } for (int i = 0; i < tabs.length;) { if (tabs[i]['is_show'] != "1") { tabs.removeAt(i); } else { i++; } } List contentWidgets = tabs.map((item) { BaseTabModel model = BaseTabModel.fromJson(item); //首页底部创建的item,把抖券判断置true item['is_bottom_video'] = true; return PageFactory.create(model.skipIdentifier, item); }).toList(); if (_currentIndex >= contentWidgets.length) { _currentIndex = 0; } return WillPopScope( onWillPop: () async { print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>HomepageBack>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>"); EventUtil.instance.fire("HomepageSignOut"); // 退出app // await SystemChannels.platform.invokeMethod('SystemNavigator.pop'); return true; }, child: Scaffold( body: IndexedStack( index: _currentIndex, children: contentWidgets, ), //底部导航栏 bottomNavigationBar: createBottomNavigationBar(tabs), ), ); } Widget createBottomNavigationBar(List> tabs) { List items = List(); for (int i = 0; i < tabs.length; i++) { BaseTabModel model = BaseTabModel.fromJson(tabs[i]); String icon = ImageUtil.getUrl(model.icon); String selectedIcon = ImageUtil.getUrl(model.chooseIcon ?? model.icon); String textColor = model.fontColor; String chooseColor = model.chooseColor ?? textColor; if (model.isShow == "1") { items.add(BottomNavigationBarItem( icon: Container( width: 24, height: 24, margin: EdgeInsets.only(bottom: 4), child: CachedNetworkImage( imageUrl: _currentIndex == i ? selectedIcon : icon, fit: BoxFit.fitWidth, ), ), title: Text( model.name, style: TextStyle(fontSize: 11, color: HexColor.fromHex(_currentIndex == i ? chooseColor : textColor)), ))); } } if (items.length < 2) { return Container(); } String bgColor = '#ffffff'; if (tabs.first != null) { BaseTabModel model = BaseTabModel.fromJson(tabs.first); bgColor = model.bgColor ?? bgColor; } return BottomNavigationBar( backgroundColor: HexColor.fromHex(bgColor), type: BottomNavigationBarType.fixed, selectedFontSize: 11, unselectedFontSize: 11, currentIndex: _currentIndex, elevation: 0, onTap: ((index) async { BaseTabModel model = BaseTabModel.fromJson(tabs[index]); if (await _checkLimit(model)) { ///避免同一个页面多次点击多次重绘 if (_currentIndex == index) { return; } else { /// 如果是外链,直接打开原生WebView if (model?.skipIdentifier == 'pub.flutter.url') { RouterUtil.openWebview(model?.url, context); return; } setState(() { _currentIndex = index; }); EventUtil.instance.fire(model?.skipIdentifier); } } }), //底部导航栏 items: items); } // Widget createBottomNavigationBarNew(List> tabs) { // // List items = List(); // for (int i = 0; i < tabs.length; i++) { // BaseTabModel model = BaseTabModel.fromJson(tabs[i]); // String icon = ImageUtil.getUrl(model.icon); // String selectedIcon = ImageUtil.getUrl(model.chooseIcon ?? model.icon); // String textColor = model.fontColor; // String chooseColor = model.chooseColor ?? textColor; // // if (model.isShow == "1") { // items.add(TabItem( // icon: Image.network(icon ?? ''), // activeIcon: Image.network(selectedIcon ?? ''), // title: model.name ?? '' // )); // } // } // // if (items.length < 2) { // return Container(); // } // String bgColor = '#ffffff'; // String textColor = '#999999'; // String activeColor = '#FF4242'; // if (tabs.first != null) { // BaseTabModel model = BaseTabModel.fromJson(tabs.first); // bgColor = model.bgColor ?? bgColor; // textColor = model?.fontColor ?? textColor; // activeColor = model?.chooseColor ?? activeColor; // } // // return ConvexAppBar( // elevation: 0, // backgroundColor: HexColor.fromHex(bgColor), // items: items, // height: 50, // color: HexColor.fromHex(textColor), // activeColor: HexColor.fromHex(activeColor), // initialActiveIndex: _currentIndex, // style: TabStyle.react, // onTap: (int index) async { // BaseTabModel model = BaseTabModel.fromJson(tabs[index]); // if (await _checkLimit(model)) { // ///避免同一个页面多次点击多次重绘 // if (_currentIndex == index) { // return; // } else { // setState(() { // _currentIndex = index; // }); // } // } // }, // ); // } Future _checkLimit(BaseTabModel model) async { if (model.requiredLogin == '1') { UserInfoModel user = await Provider.of(context, listen: false).getUserInfoModel(); print(user.toString()); if (user?.token == null || user.token == '') { print('need login...'); RouterUtil.goLogin(context); return false; } } return true; } /// /// 各种弹窗 /// 1、用户协议弹窗 搬到启动页之前显示了 /// 2、通知栏开启弹窗 /// 3、活动弹窗 /// Future _showPolicy() async { await Future.delayed(Duration(milliseconds: 1000), () async { // 通知弹窗 ///每打开5次检查一次权限 String showNotiPermissionTime = await SharedPreferencesUtil.getStringValue(Constants.showNotiPermissionTime, defaultVal: "5"); int timer = int.tryParse(showNotiPermissionTime) ?? 0; if (timer % 5 == 0) { timer++; SharedPreferencesUtil.setStringValue(Constants.showNotiPermissionTime, timer.toString()); if (!await Permission.storage.isGranted) { await NotificationSettingDialogNew.show(context); } String notificationAgree = await SharedPreferencesUtil.getStringValue(Constants.notificationAgree, defaultVal: "0"); if (notificationAgree == "1" && await Permission.notification.isGranted) { ///啥也不干 } else { if (notificationAgree == "0" || !await Permission.notification.isGranted) { bool isGranted = await Permission.notification.isGranted; var result = await showDialog( context: context, child: NotificationDialog( isGranted: isGranted, )); if (result != null && result) { SharedPreferencesUtil.setStringValue(Constants.notificationAgree, "1"); if (!await Permission.notification.isGranted) { if (Platform.isIOS) { openAppSettings(); } else { await NativeUtil.openAppSettings(); } } } } } } // 活动弹窗 await AdvertisingDialog.show(context); IntellectCreate.checkAndCreateFirst(context); }); await Future.delayed(Duration(seconds: 3), () async { //debug app不更新 app更新插件 await AppUpdateUtil.initXUpdate(); // 检查app更新 await AppUpdateUtil.updateApp(context); }); } // 场景还原,记录邀请码 void _restore(MLSDKScene scene) { // const bool inProduction = const bool.fromEnvironment("dart.vm.product"); // if (!inProduction) { // // 非release环境,弹窗测试 // showAlert('要还原的路径为:' + scene.className + '\n' + scene.params.toString(), // context); // } Logger.debug('要还原的路径为:' + scene.className); try { Map params = Map.from(scene.params); if (params.containsKey('tgid')) { String tgid = params['tgid'].toString(); // 记录邀请码到本地 MobUtil.storeInvitedCode(tgid); } } catch (e) { Logger.error(e); } } //app存在后台时候的还原 void _onEvent(Object event) { Logger.debug('返回的内容: $event'); try { if (null != event) { Map params = Map.from(event); // const bool inProduction = const bool.fromEnvironment("dart.vm.product"); // if (!inProduction) { // // 非release环境,弹窗测试 // showAlert('要还原的路径为[活着]:$event', context); // } if (params['params'].containsKey('tgid')) { String tgid = params['params']['tgid'].toString(); // 记录邀请码到本地 MobUtil.storeInvitedCode(tgid); } } } catch (e) { Logger.error(e); } } void _onError(Object error) { Logger.error('返回的错误: $error'); } void showAlert(String text, BuildContext context) { showDialog( context: context, builder: (BuildContext context) => CupertinoAlertDialog(title: new Text("提示"), content: new Text(text), actions: [ new FlatButton( child: new Text("OK"), onPressed: () { Navigator.of(context).pop(); }, ) ])); } @override void onPaused() { print("首页调用不可见"); IntellectCreate.setCheck(false); } @override void onResume() { print("首页调用可见"); IntellectCreate.setCheck(true); } @override // TODO: implement wantKeepAlive bool get wantKeepAlive => true; ///设置定向推送 void setAlias() async { ///如果没有开启通知则设置别名 if (await SharedPreferencesUtil.getStringValue(Constants.notificationAgree, defaultVal: "0") == "1") { UserInfoModel userInfo = UserInfoNotifier?.staitcUserInfo; var setting = await NativeUtil.getSetting(); String masterId = setting['master_id']; Logger.log("我的Alias: " + masterId + "_" + userInfo?.userId); if (!EmptyUtil.isEmpty(userInfo.userId) && !EmptyUtil.isEmpty(masterId)) { print("设置标签" + masterId + "_" + userInfo.userId); await MobPushUtil.restartPush(); await MobPushUtil.setAlias(masterId + "_" + userInfo.userId); SharedPreferencesUtil.setStringValue(Constants.isSetTag, "1"); } } } } final RouteObserver lifeObserver = RouteObserver(); abstract class LifeState extends State with RouteAware { @override void initState() { super.initState(); } @override void didChangeDependencies() { lifeObserver.subscribe(this, ModalRoute.of(context)); super.didChangeDependencies(); } @override void dispose() { lifeObserver.unsubscribe(this); super.dispose(); } void didPop() { onPaused(); } void didPopNext() { onResume(); print("回到首页"); setState(() {}); } void didPush() { onResume(); } void didPushNext() { onPaused(); } void onResume(); void onPaused(); }