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

339 lines
11 KiB

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