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

293 lines
9.8 KiB

  1. import 'dart:convert' as convert;
  2. import 'dart: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:moblink/moblink.dart';
  10. import 'package:mobpush_plugin/mobpush_custom_message.dart';
  11. import 'package:mobpush_plugin/mobpush_notify_message.dart';
  12. import 'package:mobpush_plugin/mobpush_plugin.dart';
  13. import 'package:provider/provider.dart';
  14. import 'package:zhiying_base_widget/dialog/global_dialog/activity_dialog/activity_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/global_dialog/policy_dialog/policy_dialog.dart';
  18. import 'package:zhiying_base_widget/utils/contants.dart';
  19. import 'package:zhiying_base_widget/utils/mob_push_util.dart';
  20. import 'package:zhiying_comm/models/base/base_tab_model.dart';
  21. import 'package:zhiying_comm/util/image_util.dart';
  22. import 'package:zhiying_comm/util/mob_util/mob_util.dart';
  23. import 'package:sharesdk_plugin/sharesdk_plugin.dart';
  24. import 'package:zhiying_comm/util/shared_prefe_util.dart';
  25. import 'package:zhiying_comm/util/update/app_update_util.dart';
  26. import 'package:zhiying_comm/zhiying_comm.dart';
  27. import 'package:zhiying_comm/util/event_util/login_success_event.dart';
  28. import 'package:zhiying_comm/util/event_util/event_util.dart';
  29. import 'package:zhiying_comm/util/event_util/log_out.dart';
  30. class HomePage extends StatefulWidget {
  31. HomePage({Key key}) : super(key: key);
  32. @override
  33. _HomePageState createState() => _HomePageState();
  34. }
  35. class _HomePageState extends State<HomePage> with WidgetsBindingObserver {
  36. int _currentIndex = 0;
  37. List<Map<String, dynamic>> _data = List();
  38. static const EventChannel _eventChannel = const EventChannel('JAVA_TO_FLUTTER');
  39. @override
  40. void initState() {
  41. WidgetsBinding.instance.addObserver(this);
  42. String data = BaseSettingModel.setting.tab['data'];
  43. try {
  44. List list = convert.jsonDecode(data);
  45. _data = list.map((item) {
  46. return Map<String, dynamic>.from(item);
  47. }).toList();
  48. Logger.debug(_data);
  49. } catch (error) {
  50. Logger.error(error);
  51. }
  52. Constants.isShowIntellectDialog = false;
  53. AppUpdateUtil.updateApp(context);
  54. TaobaoAuth.initAuth(context);
  55. // 弹窗
  56. _showPolicy();
  57. Moblink.uploadPrivacyPermissionStatus(1, (bool success) {});
  58. SharesdkPlugin.uploadPrivacyPermissionStatus(1, (bool success) {});
  59. // 是安卓系统,Android场景还原的实现
  60. /*if (defaultTargetPlatform == TargetPlatform.android) {
  61. }*/
  62. //app后台杀死时候的还原
  63. Moblink.restoreScene(_restore);
  64. // 监听开始(传递监听到原生端,用户监听场景还原的数据回传回来)
  65. _eventChannel.receiveBroadcastStream().listen(_onEvent, onError: _onError);
  66. MobPushUtil.addPushReceiver();
  67. EventUtil.instance.on<LoginSuccessEvent>().listen((event) async {
  68. UserInfoModel userInfo = UserInfoNotifier?.staitcUserInfo;
  69. var setting = await NativeUtil.getSetting();
  70. String masterId = setting['master_id'];
  71. Logger.log("我的Alias: " + masterId + "_" + userInfo?.userId);
  72. if (!EmptyUtil.isEmpty(userInfo.userId) && !EmptyUtil.isEmpty(masterId)) {
  73. MobPushUtil.setAlias(masterId + "_" + userInfo.userId);
  74. }
  75. });
  76. EventUtil.instance.on<LogOut>().listen((event) {
  77. MobPushUtil.deleteAlias();
  78. });
  79. super.initState();
  80. }
  81. @override
  82. void dispose() {
  83. WidgetsBinding.instance.removeObserver(this);
  84. super.dispose();
  85. }
  86. @override
  87. void didChangeAppLifecycleState(AppLifecycleState state) {
  88. ///智能粘贴板
  89. IntellectCreate.checkAndCreate(state, context);
  90. super.didChangeAppLifecycleState(state);
  91. }
  92. @override
  93. Widget build(BuildContext context) {
  94. ScreenUtil.init(context, width: 750, height: 1334);
  95. Logger.debug('home_page build');
  96. List<Map<String, dynamic>> tabs = _data;
  97. if (tabs == null || tabs.length == 0) {
  98. return Scaffold();
  99. }
  100. List<Widget> contentWidgets = tabs.map((item) {
  101. BaseTabModel model = BaseTabModel.fromJson(item);
  102. return PageFactory.create(model.skipIdentifier, item);
  103. }).toList();
  104. if (_currentIndex >= contentWidgets.length) {
  105. _currentIndex = 0;
  106. }
  107. return Scaffold(
  108. body: IndexedStack(
  109. index: _currentIndex,
  110. children: contentWidgets,
  111. ),
  112. //底部导航栏
  113. bottomNavigationBar: createBottomNavigationBar(tabs),
  114. );
  115. }
  116. Widget createBottomNavigationBar(List<Map<String, dynamic>> tabs) {
  117. List<BottomNavigationBarItem> items = List<BottomNavigationBarItem>();
  118. for (int i = 0; i < tabs.length; i++) {
  119. BaseTabModel model = BaseTabModel.fromJson(tabs[i]);
  120. String icon = ImageUtil.getUrl(model.icon);
  121. String selectedIcon = ImageUtil.getUrl(model.chooseIcon ?? model.icon);
  122. String textColor = model.fontColor;
  123. String chooseColor = model.chooseColor ?? textColor;
  124. if (model.isShow == "1") {
  125. items.add(BottomNavigationBarItem(
  126. icon: Container(
  127. width: 24,
  128. height: 24,
  129. margin: EdgeInsets.only(bottom: 4),
  130. child: CachedNetworkImage(
  131. imageUrl: _currentIndex == i ? selectedIcon : icon,
  132. fit: BoxFit.fitWidth,
  133. ),
  134. ),
  135. title: Text(
  136. model.name,
  137. style: TextStyle(fontSize: 11, color: HexColor.fromHex(_currentIndex == i ? chooseColor : textColor)),
  138. )));
  139. }
  140. }
  141. if (items.length < 2) {
  142. return Container();
  143. }
  144. String bgColor = '#ffffff';
  145. if (tabs.first != null) {
  146. BaseTabModel model = BaseTabModel.fromJson(tabs.first);
  147. bgColor = model.bgColor ?? bgColor;
  148. }
  149. return BottomNavigationBar(
  150. backgroundColor: HexColor.fromHex(bgColor),
  151. type: BottomNavigationBarType.fixed,
  152. selectedFontSize: 11,
  153. unselectedFontSize: 11,
  154. currentIndex: _currentIndex,
  155. elevation: 0,
  156. onTap: ((index) async {
  157. BaseTabModel model = BaseTabModel.fromJson(tabs[index]);
  158. if (await _checkLimit(model)) {
  159. setState(() {
  160. _currentIndex = index;
  161. });
  162. }
  163. }),
  164. //底部导航栏
  165. items: items);
  166. }
  167. Future<bool> _checkLimit(BaseTabModel model) async {
  168. if (model.requiredLogin == '1') {
  169. UserInfoModel user = await Provider.of<UserInfoNotifier>(context, listen: false).getUserInfoModel();
  170. print(user.toString());
  171. if (user?.token == null || user.token == '') {
  172. print('need login...');
  173. RouterUtil.goLogin(context);
  174. return false;
  175. }
  176. }
  177. return true;
  178. }
  179. ///
  180. /// 各种弹窗
  181. /// 1、用户协议弹窗
  182. /// 2、通知栏开启弹窗
  183. /// 3、活动弹窗
  184. ///
  185. Future _showPolicy() async {
  186. // 协议弹窗
  187. String isShowPolicy = await SharedPreferencesUtil.getStringValue(Constants.isShowPolicy);
  188. if (isShowPolicy == null || isShowPolicy != '1') {
  189. bool isAccept = await PolicyDialog.show(context);
  190. if (!isAccept) {
  191. exit(0);
  192. } else {
  193. await SharedPreferencesUtil.setStringValue(Constants.isShowPolicy, "1");
  194. }
  195. }
  196. // 通知弹窗
  197. String isShowNotiPermission = await SharedPreferencesUtil.getStringValue(Constants.isShowNotiPermission);
  198. if (isShowNotiPermission == null || isShowNotiPermission != '1') {
  199. await NotificationSettingDialog.show(context);
  200. await SharedPreferencesUtil.setStringValue(Constants.isShowNotiPermission, "1");
  201. }
  202. // 活动弹窗
  203. await ActivityDialog.show(context);
  204. IntellectCreate.checkAndCreateFirst(context);
  205. }
  206. // 场景还原,记录邀请码
  207. void _restore(MLSDKScene scene) {
  208. // const bool inProduction = const bool.fromEnvironment("dart.vm.product");
  209. // if (!inProduction) {
  210. // // 非release环境,弹窗测试
  211. // showAlert('要还原的路径为:' + scene.className + '\n' + scene.params.toString(),
  212. // context);
  213. // }
  214. Logger.debug('要还原的路径为:' + scene.className);
  215. try {
  216. Map<String, dynamic> params = Map<String, dynamic>.from(scene.params);
  217. if (params.containsKey('tgid')) {
  218. String tgid = params['tgid'].toString();
  219. // 记录邀请码到本地
  220. MobUtil.storeInvitedCode(tgid);
  221. }
  222. } catch (e) {
  223. Logger.error(e);
  224. }
  225. }
  226. //app存在后台时候的还原
  227. void _onEvent(Object event) {
  228. Logger.debug('返回的内容: $event');
  229. try {
  230. if (null != event) {
  231. Map<String, dynamic> params = Map<String, dynamic>.from(event);
  232. // const bool inProduction = const bool.fromEnvironment("dart.vm.product");
  233. // if (!inProduction) {
  234. // // 非release环境,弹窗测试
  235. // showAlert('要还原的路径为[活着]:$event', context);
  236. // }
  237. if (params['params'].containsKey('tgid')) {
  238. String tgid = params['params']['tgid'].toString();
  239. // 记录邀请码到本地
  240. MobUtil.storeInvitedCode(tgid);
  241. }
  242. }
  243. } catch (e) {
  244. Logger.error(e);
  245. }
  246. }
  247. void _onError(Object error) {
  248. Logger.error('返回的错误: $error');
  249. }
  250. void showAlert(String text, BuildContext context) {
  251. showDialog(
  252. context: context,
  253. builder: (BuildContext context) =>
  254. CupertinoAlertDialog(title: new Text("提示"), content: new Text(text), actions: <Widget>[
  255. new FlatButton(
  256. child: new Text("OK"),
  257. onPressed: () {
  258. Navigator.of(context).pop();
  259. },
  260. )
  261. ]));
  262. }
  263. }