基础组件库
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.

home_page.dart 16 KiB

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