基础组件库
You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

558 lines
18 KiB

  1. import 'dart:async';
  2. import 'dart:convert' as convert;
  3. import 'dart:io';
  4. import 'package:cached_network_image/cached_network_image.dart';
  5. import 'package:flutter/cupertino.dart';
  6. import 'package:flutter/foundation.dart';
  7. import 'package:flutter/material.dart';
  8. import 'package:flutter/services.dart';
  9. import 'package:flutter/widgets.dart';
  10. import 'package:moblink/moblink.dart';
  11. import 'package:mobcommonlib/mobcommonlib.dart';
  12. import 'package:permission_handler/permission_handler.dart';
  13. import 'package:provider/provider.dart';
  14. import 'package:zhiying_base_widget/dialog/global_dialog/advertising_dialog/advertising_dialog.dart';
  15. import 'package:zhiying_base_widget/dialog/global_dialog/intellect_search_goods_dialog/intellect_create.dart';
  16. import 'package:zhiying_base_widget/dialog/global_dialog/notification_setting_dialog/notification_setting_dialog.dart';
  17. import 'package:zhiying_base_widget/dialog/notification_dialog/notification_dialog.dart';
  18. import 'package:zhiying_base_widget/dialog/tip_dialog/tip_dialog.dart';
  19. import 'package:zhiying_base_widget/models/app_config_model.dart';
  20. import 'package:zhiying_base_widget/pages/custom_page/event/reload_event.dart';
  21. import 'package:zhiying_base_widget/utils/contants.dart';
  22. import 'package:zhiying_base_widget/utils/mob_push_util.dart';
  23. import 'package:zhiying_base_widget/widgets/restart_widget/restart_widget.dart';
  24. import 'package:zhiying_comm/models/base/base_tab_model.dart';
  25. import 'package:zhiying_comm/util/image_util.dart';
  26. import 'package:zhiying_comm/util/mob_util/mob_util.dart';
  27. import 'package:sharesdk_plugin/sharesdk_plugin.dart';
  28. import 'package:zhiying_comm/util/shared_prefe_util.dart';
  29. import 'package:zhiying_comm/util/update/app_update_util.dart';
  30. import 'package:zhiying_comm/zhiying_comm.dart';
  31. import 'package:zhiying_comm/util/event_util/login_success_event.dart';
  32. import 'package:zhiying_comm/util/event_util/event_util.dart';
  33. import 'package:zhiying_comm/util/event_util/log_out.dart';
  34. import 'package:flutter_alibc/flutter_alibc.dart';
  35. import '../../models/app_config_model.dart';
  36. class HomeCenterPage extends StatefulWidget {
  37. @override
  38. _HomeCenterPageState createState() => _HomeCenterPageState();
  39. }
  40. class _HomeCenterPageState extends State<HomeCenterPage> {
  41. @override
  42. Widget build(BuildContext context) {
  43. return RestartWidget(child: HomePage());
  44. }
  45. }
  46. class HomePage extends StatefulWidget {
  47. HomePage({Key key}) : super(key: key);
  48. @override
  49. _HomePageState createState() => _HomePageState();
  50. }
  51. class _HomePageState extends State<HomePage> with WidgetsBindingObserver, TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  52. int _currentIndex = 0;
  53. List<Map<String, dynamic>> _data = List();
  54. static const EventChannel _eventChannel = const EventChannel('JAVA_TO_FLUTTER');
  55. StreamSubscription streamSubscription;
  56. StreamSubscription reloadSubscription;
  57. StreamSubscription logOutSubscription;
  58. StreamSubscription loginSubscription;
  59. StreamSubscription eventChannelSubscription;
  60. @override
  61. void initState() {
  62. ///初始化一些数据
  63. initAsync();
  64. //如果登出则重新打开首页
  65. streamSubscription = EventUtil.instance.on<LogOut>().listen((event) async {
  66. UserInfoModel user = await Provider.of<UserInfoNotifier>(context, listen: false).getUserInfoModel();
  67. user.token = '';
  68. Navigator.maybePop(context);
  69. print("重启1");
  70. Navigator.pushReplacementNamed(context, "/homePage");
  71. });
  72. reloadSubscription = EventUtil.instance.on<ReloadEvent>().listen((event) async {
  73. print("重启2");
  74. await BaseSettingModel.init(isGetCache: false);
  75. RestartWidget.restartApp(context);
  76. });
  77. super.initState();
  78. }
  79. ///初始化各种监听
  80. initAsync() async {
  81. try {
  82. WidgetsBinding.instance.addObserver(this);
  83. // 监听开始(传递监听到原生端,用户监听场景还原的数据回传回来)
  84. eventChannelSubscription = _eventChannel.receiveBroadcastStream().listen(_onEvent, onError: _onError);
  85. ///渲染完第一帧后调用
  86. WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
  87. int delay = ((num.tryParse(AppConfigModel.appStartDelay) ?? 0.5) * 1000).toInt();
  88. print("延时" + AppConfigModel.appStartDelay.toString());
  89. Timer(Duration(milliseconds: delay), () {
  90. NativeUtil.notifyInitSuccess();
  91. //app后台杀死时候的还原
  92. Moblink.restoreScene(_restore);
  93. });
  94. });
  95. initBaseSet();
  96. Constants.isShowIntellectDialog = false;
  97. TaobaoAuth.initAuth(context);
  98. //弹窗
  99. _showPolicy();
  100. // mob锁粉隐私协议提交
  101. Moblink.uploadPrivacyPermissionStatus(1, (bool success) {});
  102. // mob分享SDK隐私协议提交
  103. SharesdkPlugin.uploadPrivacyPermissionStatus(1, (bool success) {});
  104. // mob短信SDK隐私协议提交
  105. Mobcommonlib.submitPolicyGrantResult(true, (dynamic ret, Map err) => {});
  106. ///设置推送标识
  107. setAlias();
  108. // 是安卓系统,Android场景还原的实现
  109. /*if (defaultTargetPlatform == TargetPlatform.android) {
  110. }*/
  111. logOutSubscription = EventUtil.instance.on<LogOut>().listen((event) {
  112. MobPushUtil.deleteAlias();
  113. SharedPreferencesUtil.setStringValue(Constants.isSetTag, "0");
  114. });
  115. MobPushUtil.addPushReceiver();
  116. loginSubscription = EventUtil.instance.on<LoginSuccessEvent>().listen((event) async {
  117. setAlias();
  118. });
  119. } catch (e, s) {
  120. print(e);
  121. print(s);
  122. }
  123. }
  124. initBaseSet() {
  125. String data = BaseSettingModel.setting.tab['data'];
  126. try {
  127. List list = convert.jsonDecode(data);
  128. _data = list.map((item) {
  129. return Map<String, dynamic>.from(item);
  130. }).toList();
  131. Logger.debug(_data);
  132. } catch (error) {
  133. Logger.error(error);
  134. }
  135. }
  136. @override
  137. void dispose() {
  138. print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Homepagedispose>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
  139. WidgetsBinding.instance.removeObserver(this);
  140. streamSubscription.cancel();
  141. reloadSubscription?.cancel();
  142. logOutSubscription?.cancel();
  143. loginSubscription?.cancel();
  144. eventChannelSubscription?.cancel();
  145. super.dispose();
  146. }
  147. @override
  148. void didChangeAppLifecycleState(AppLifecycleState state) {
  149. ///智能粘贴板
  150. IntellectCreate.checkAndCreate(state, context);
  151. super.didChangeAppLifecycleState(state);
  152. }
  153. @override
  154. Widget build(BuildContext context) {
  155. ScreenUtil.init(context, width: 750, height: 1334);
  156. Logger.debug('home_page build');
  157. List<Map<String, dynamic>> tabs = _data;
  158. if (tabs == null || tabs.length == 0) {
  159. return Scaffold();
  160. }
  161. for (int i = 0; i < tabs.length;) {
  162. if (tabs[i]['is_show'] != "1") {
  163. tabs.removeAt(i);
  164. } else {
  165. i++;
  166. }
  167. }
  168. List<Widget> contentWidgets = tabs.map((item) {
  169. BaseTabModel model = BaseTabModel.fromJson(item);
  170. //首页底部创建的item,把抖券判断置true
  171. item['is_bottom_video'] = true;
  172. return PageFactory.create(model.skipIdentifier, item);
  173. }).toList();
  174. if (_currentIndex >= contentWidgets.length) {
  175. _currentIndex = 0;
  176. }
  177. return WillPopScope(
  178. onWillPop: () async {
  179. print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>HomepageBack>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
  180. EventUtil.instance.fire("HomepageSignOut");
  181. // 退出app
  182. // await SystemChannels.platform.invokeMethod('SystemNavigator.pop');
  183. return true;
  184. },
  185. child: Scaffold(
  186. body: IndexedStack(
  187. index: _currentIndex,
  188. children: contentWidgets,
  189. ),
  190. //底部导航栏
  191. bottomNavigationBar: createBottomNavigationBar(tabs),
  192. ),
  193. );
  194. }
  195. Widget createBottomNavigationBar(List<Map<String, dynamic>> tabs) {
  196. List<BottomNavigationBarItem> items = List<BottomNavigationBarItem>();
  197. for (int i = 0; i < tabs.length; i++) {
  198. BaseTabModel model = BaseTabModel.fromJson(tabs[i]);
  199. String icon = ImageUtil.getUrl(model.icon);
  200. String selectedIcon = ImageUtil.getUrl(model.chooseIcon ?? model.icon);
  201. String textColor = model.fontColor;
  202. String chooseColor = model.chooseColor ?? textColor;
  203. if (model.isShow == "1") {
  204. items.add(BottomNavigationBarItem(
  205. icon: Container(
  206. width: 24,
  207. height: 24,
  208. margin: EdgeInsets.only(bottom: 4),
  209. child: CachedNetworkImage(
  210. imageUrl: _currentIndex == i ? selectedIcon : icon,
  211. fit: BoxFit.fitWidth,
  212. ),
  213. ),
  214. title: Text(
  215. model.name,
  216. style: TextStyle(fontSize: 11, color: HexColor.fromHex(_currentIndex == i ? chooseColor : textColor)),
  217. )));
  218. }
  219. }
  220. if (items.length < 2) {
  221. return Container();
  222. }
  223. String bgColor = '#ffffff';
  224. if (tabs.first != null) {
  225. BaseTabModel model = BaseTabModel.fromJson(tabs.first);
  226. bgColor = model.bgColor ?? bgColor;
  227. }
  228. return BottomNavigationBar(
  229. backgroundColor: HexColor.fromHex(bgColor),
  230. type: BottomNavigationBarType.fixed,
  231. selectedFontSize: 11,
  232. unselectedFontSize: 11,
  233. currentIndex: _currentIndex,
  234. elevation: 0,
  235. onTap: ((index) async {
  236. BaseTabModel model = BaseTabModel.fromJson(tabs[index]);
  237. if (await _checkLimit(model)) {
  238. ///避免同一个页面多次点击多次重绘
  239. if (_currentIndex == index) {
  240. return;
  241. } else {
  242. /// 如果是外链,直接打开原生WebView
  243. if (model?.skipIdentifier == 'pub.flutter.url') {
  244. RouterUtil.openWebview(model?.url, context);
  245. return;
  246. }
  247. setState(() {
  248. _currentIndex = index;
  249. });
  250. EventUtil.instance.fire(model?.skipIdentifier);
  251. }
  252. }
  253. }),
  254. //底部导航栏
  255. items: items);
  256. }
  257. // Widget createBottomNavigationBarNew(List<Map<String, dynamic>> tabs) {
  258. //
  259. // List<TabItem> items = List<TabItem>();
  260. // for (int i = 0; i < tabs.length; i++) {
  261. // BaseTabModel model = BaseTabModel.fromJson(tabs[i]);
  262. // String icon = ImageUtil.getUrl(model.icon);
  263. // String selectedIcon = ImageUtil.getUrl(model.chooseIcon ?? model.icon);
  264. // String textColor = model.fontColor;
  265. // String chooseColor = model.chooseColor ?? textColor;
  266. //
  267. // if (model.isShow == "1") {
  268. // items.add(TabItem<Image>(
  269. // icon: Image.network(icon ?? ''),
  270. // activeIcon: Image.network(selectedIcon ?? ''),
  271. // title: model.name ?? ''
  272. // ));
  273. // }
  274. // }
  275. //
  276. // if (items.length < 2) {
  277. // return Container();
  278. // }
  279. // String bgColor = '#ffffff';
  280. // String textColor = '#999999';
  281. // String activeColor = '#FF4242';
  282. // if (tabs.first != null) {
  283. // BaseTabModel model = BaseTabModel.fromJson(tabs.first);
  284. // bgColor = model.bgColor ?? bgColor;
  285. // textColor = model?.fontColor ?? textColor;
  286. // activeColor = model?.chooseColor ?? activeColor;
  287. // }
  288. //
  289. // return ConvexAppBar(
  290. // elevation: 0,
  291. // backgroundColor: HexColor.fromHex(bgColor),
  292. // items: items,
  293. // height: 50,
  294. // color: HexColor.fromHex(textColor),
  295. // activeColor: HexColor.fromHex(activeColor),
  296. // initialActiveIndex: _currentIndex,
  297. // style: TabStyle.react,
  298. // onTap: (int index) async {
  299. // BaseTabModel model = BaseTabModel.fromJson(tabs[index]);
  300. // if (await _checkLimit(model)) {
  301. // ///避免同一个页面多次点击多次重绘
  302. // if (_currentIndex == index) {
  303. // return;
  304. // } else {
  305. // setState(() {
  306. // _currentIndex = index;
  307. // });
  308. // }
  309. // }
  310. // },
  311. // );
  312. // }
  313. Future<bool> _checkLimit(BaseTabModel model) async {
  314. if (model.requiredLogin == '1') {
  315. UserInfoModel user = await Provider.of<UserInfoNotifier>(context, listen: false).getUserInfoModel();
  316. print(user.toString());
  317. if (user?.token == null || user.token == '') {
  318. print('need login...');
  319. RouterUtil.goLogin(context);
  320. return false;
  321. }
  322. }
  323. return true;
  324. }
  325. ///
  326. /// 各种弹窗
  327. /// 1、用户协议弹窗 搬到启动页之前显示了
  328. /// 2、通知栏开启弹窗
  329. /// 3、活动弹窗
  330. ///
  331. Future _showPolicy() async {
  332. await Future.delayed(Duration(milliseconds: 1000), () async {
  333. // 通知弹窗
  334. ///每打开5次检查一次权限
  335. String showNotiPermissionTime = await SharedPreferencesUtil.getStringValue(Constants.showNotiPermissionTime, defaultVal: "5");
  336. int timer = int.tryParse(showNotiPermissionTime) ?? 0;
  337. if (timer % 5 == 0) {
  338. timer++;
  339. SharedPreferencesUtil.setStringValue(Constants.showNotiPermissionTime, timer.toString());
  340. if (!await Permission.storage.isGranted) {
  341. await NotificationSettingDialogNew.show(context);
  342. }
  343. String notificationAgree = await SharedPreferencesUtil.getStringValue(Constants.notificationAgree, defaultVal: "0");
  344. if (notificationAgree == "1" && await Permission.notification.isGranted) {
  345. ///啥也不干
  346. } else {
  347. if (notificationAgree == "0" || !await Permission.notification.isGranted) {
  348. bool isGranted = await Permission.notification.isGranted;
  349. var result = await showDialog(
  350. context: context,
  351. child: NotificationDialog(
  352. isGranted: isGranted,
  353. ));
  354. if (result != null && result) {
  355. SharedPreferencesUtil.setStringValue(Constants.notificationAgree, "1");
  356. if (!await Permission.notification.isGranted) {
  357. if (Platform.isIOS) {
  358. openAppSettings();
  359. } else {
  360. await NativeUtil.openAppSettings();
  361. }
  362. }
  363. }
  364. }
  365. }
  366. }
  367. // 活动弹窗
  368. await AdvertisingDialog.show(context);
  369. IntellectCreate.checkAndCreateFirst(context);
  370. });
  371. await Future.delayed(Duration(seconds: 3), () async {
  372. //debug app不更新 app更新插件
  373. await AppUpdateUtil.initXUpdate();
  374. // 检查app更新
  375. await AppUpdateUtil.updateApp(context);
  376. });
  377. }
  378. // 场景还原,记录邀请码
  379. void _restore(MLSDKScene scene) {
  380. // const bool inProduction = const bool.fromEnvironment("dart.vm.product");
  381. // if (!inProduction) {
  382. // // 非release环境,弹窗测试
  383. // showAlert('要还原的路径为:' + scene.className + '\n' + scene.params.toString(),
  384. // context);
  385. // }
  386. Logger.debug('要还原的路径为:' + scene.className);
  387. try {
  388. Map<String, dynamic> params = Map<String, dynamic>.from(scene.params);
  389. if (params.containsKey('tgid')) {
  390. String tgid = params['tgid'].toString();
  391. // 记录邀请码到本地
  392. MobUtil.storeInvitedCode(tgid);
  393. }
  394. } catch (e) {
  395. Logger.error(e);
  396. }
  397. }
  398. //app存在后台时候的还原
  399. void _onEvent(Object event) {
  400. Logger.debug('返回的内容: $event');
  401. try {
  402. if (null != event) {
  403. Map<String, dynamic> params = Map<String, dynamic>.from(event);
  404. // const bool inProduction = const bool.fromEnvironment("dart.vm.product");
  405. // if (!inProduction) {
  406. // // 非release环境,弹窗测试
  407. // showAlert('要还原的路径为[活着]:$event', context);
  408. // }
  409. if (params['params'].containsKey('tgid')) {
  410. String tgid = params['params']['tgid'].toString();
  411. // 记录邀请码到本地
  412. MobUtil.storeInvitedCode(tgid);
  413. }
  414. }
  415. } catch (e) {
  416. Logger.error(e);
  417. }
  418. }
  419. void _onError(Object error) {
  420. Logger.error('返回的错误: $error');
  421. }
  422. void showAlert(String text, BuildContext context) {
  423. showDialog(
  424. context: context,
  425. builder: (BuildContext context) => CupertinoAlertDialog(title: new Text("提示"), content: new Text(text), actions: <Widget>[
  426. new FlatButton(
  427. child: new Text("OK"),
  428. onPressed: () {
  429. Navigator.of(context).pop();
  430. },
  431. )
  432. ]));
  433. }
  434. @override
  435. void onPaused() {
  436. print("首页调用不可见");
  437. IntellectCreate.setCheck(false);
  438. }
  439. @override
  440. void onResume() {
  441. print("首页调用可见");
  442. IntellectCreate.setCheck(true);
  443. }
  444. @override
  445. // TODO: implement wantKeepAlive
  446. bool get wantKeepAlive => true;
  447. ///设置定向推送
  448. void setAlias() async {
  449. ///如果没有开启通知则设置别名
  450. if (await SharedPreferencesUtil.getStringValue(Constants.notificationAgree, defaultVal: "0") == "1") {
  451. UserInfoModel userInfo = UserInfoNotifier?.staitcUserInfo;
  452. var setting = await NativeUtil.getSetting();
  453. String masterId = setting['master_id'];
  454. Logger.log("我的Alias: " + masterId + "_" + userInfo?.userId);
  455. if (!EmptyUtil.isEmpty(userInfo.userId) && !EmptyUtil.isEmpty(masterId)) {
  456. print("设置标签" + masterId + "_" + userInfo.userId);
  457. await MobPushUtil.restartPush();
  458. await MobPushUtil.setAlias(masterId + "_" + userInfo.userId);
  459. SharedPreferencesUtil.setStringValue(Constants.isSetTag, "1");
  460. }
  461. }
  462. }
  463. }
  464. final RouteObserver<Route> lifeObserver = RouteObserver();
  465. abstract class LifeState<T extends StatefulWidget> extends State<T> with RouteAware {
  466. @override
  467. void initState() {
  468. super.initState();
  469. }
  470. @override
  471. void didChangeDependencies() {
  472. lifeObserver.subscribe(this, ModalRoute.of(context));
  473. super.didChangeDependencies();
  474. }
  475. @override
  476. void dispose() {
  477. lifeObserver.unsubscribe(this);
  478. super.dispose();
  479. }
  480. void didPop() {
  481. onPaused();
  482. }
  483. void didPopNext() {
  484. onResume();
  485. print("回到首页");
  486. setState(() {});
  487. }
  488. void didPush() {
  489. onResume();
  490. }
  491. void didPushNext() {
  492. onPaused();
  493. }
  494. void onResume();
  495. void onPaused();
  496. }