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

346 lines
12 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. for (int i = 0; i < tabs.length;) {
  135. if (tabs[i]['is_show'] != "1") {
  136. tabs.removeAt(i);
  137. } else {
  138. i++;
  139. }
  140. }
  141. List<Widget> contentWidgets = tabs.map((item) {
  142. BaseTabModel model = BaseTabModel.fromJson(item);
  143. return PageFactory.create(model.skipIdentifier, item);
  144. }).toList();
  145. if (_currentIndex >= contentWidgets.length) {
  146. _currentIndex = 0;
  147. }
  148. return Scaffold(
  149. body: IndexedStack(
  150. index: _currentIndex,
  151. children: contentWidgets,
  152. ),
  153. //底部导航栏
  154. bottomNavigationBar: createBottomNavigationBar(tabs),
  155. );
  156. }
  157. Widget createBottomNavigationBar(List<Map<String, dynamic>> tabs) {
  158. List<BottomNavigationBarItem> items = List<BottomNavigationBarItem>();
  159. for (int i = 0; i < tabs.length; i++) {
  160. BaseTabModel model = BaseTabModel.fromJson(tabs[i]);
  161. String icon = ImageUtil.getUrl(model.icon);
  162. String selectedIcon = ImageUtil.getUrl(model.chooseIcon ?? model.icon);
  163. String textColor = model.fontColor;
  164. String chooseColor = model.chooseColor ?? textColor;
  165. if (model.isShow == "1") {
  166. items.add(BottomNavigationBarItem(
  167. icon: Container(
  168. width: 24,
  169. height: 24,
  170. margin: EdgeInsets.only(bottom: 4),
  171. child: CachedNetworkImage(
  172. imageUrl: _currentIndex == i ? selectedIcon : icon,
  173. fit: BoxFit.fitWidth,
  174. ),
  175. ),
  176. title: Text(
  177. model.name,
  178. style: TextStyle(fontSize: 11, color: HexColor.fromHex(_currentIndex == i ? chooseColor : textColor)),
  179. )));
  180. }
  181. }
  182. if (items.length < 2) {
  183. return Container();
  184. }
  185. String bgColor = '#ffffff';
  186. if (tabs.first != null) {
  187. BaseTabModel model = BaseTabModel.fromJson(tabs.first);
  188. bgColor = model.bgColor ?? bgColor;
  189. }
  190. return BottomNavigationBar(
  191. backgroundColor: HexColor.fromHex(bgColor),
  192. type: BottomNavigationBarType.fixed,
  193. selectedFontSize: 11,
  194. unselectedFontSize: 11,
  195. currentIndex: _currentIndex,
  196. elevation: 0,
  197. onTap: ((index) async {
  198. BaseTabModel model = BaseTabModel.fromJson(tabs[index]);
  199. if (await _checkLimit(model)) {
  200. ///避免同一个页面多次点击多次重绘
  201. if (_currentIndex == index) {
  202. return;
  203. } else {
  204. setState(() {
  205. _currentIndex = index;
  206. });
  207. }
  208. }
  209. }),
  210. //底部导航栏
  211. items: items);
  212. }
  213. Future<bool> _checkLimit(BaseTabModel model) async {
  214. if (model.requiredLogin == '1') {
  215. UserInfoModel user = await Provider.of<UserInfoNotifier>(context, listen: false).getUserInfoModel();
  216. print(user.toString());
  217. if (user?.token == null || user.token == '') {
  218. print('need login...');
  219. RouterUtil.goLogin(context);
  220. return false;
  221. }
  222. }
  223. return true;
  224. }
  225. ///
  226. /// 各种弹窗
  227. /// 1、用户协议弹窗
  228. /// 2、通知栏开启弹窗
  229. /// 3、活动弹窗
  230. ///
  231. Future _showPolicy() async {
  232. // 协议弹窗
  233. String isShowPolicy = await SharedPreferencesUtil.getStringValue(Constants.isShowPolicy);
  234. if (isShowPolicy == null || isShowPolicy != '1') {
  235. bool isAccept = await PolicyDialog.show(context);
  236. if (!isAccept) {
  237. exit(0);
  238. } else {
  239. await SharedPreferencesUtil.setStringValue(Constants.isShowPolicy, "1");
  240. }
  241. }
  242. // 通知弹窗
  243. String isShowNotiPermission = await SharedPreferencesUtil.getStringValue(Constants.isShowNotiPermission);
  244. if (isShowNotiPermission == null || isShowNotiPermission != '1') {
  245. await NotificationSettingDialog.show(context);
  246. await SharedPreferencesUtil.setStringValue(Constants.isShowNotiPermission, "1");
  247. }
  248. // 活动弹窗
  249. await ActivityDialog.show(context);
  250. await AppUpdateUtil.updateApp(context);
  251. IntellectCreate.checkAndCreateFirst(context);
  252. }
  253. // 场景还原,记录邀请码
  254. void _restore(MLSDKScene scene) {
  255. // const bool inProduction = const bool.fromEnvironment("dart.vm.product");
  256. // if (!inProduction) {
  257. // // 非release环境,弹窗测试
  258. // showAlert('要还原的路径为:' + scene.className + '\n' + scene.params.toString(),
  259. // context);
  260. // }
  261. Logger.debug('要还原的路径为:' + scene.className);
  262. try {
  263. Map<String, dynamic> params = Map<String, dynamic>.from(scene.params);
  264. if (params.containsKey('tgid')) {
  265. String tgid = params['tgid'].toString();
  266. // 记录邀请码到本地
  267. MobUtil.storeInvitedCode(tgid);
  268. }
  269. } catch (e) {
  270. Logger.error(e);
  271. }
  272. }
  273. //app存在后台时候的还原
  274. void _onEvent(Object event) {
  275. Logger.debug('返回的内容: $event');
  276. try {
  277. if (null != event) {
  278. Map<String, dynamic> params = Map<String, dynamic>.from(event);
  279. // const bool inProduction = const bool.fromEnvironment("dart.vm.product");
  280. // if (!inProduction) {
  281. // // 非release环境,弹窗测试
  282. // showAlert('要还原的路径为[活着]:$event', context);
  283. // }
  284. if (params['params'].containsKey('tgid')) {
  285. String tgid = params['params']['tgid'].toString();
  286. // 记录邀请码到本地
  287. MobUtil.storeInvitedCode(tgid);
  288. }
  289. }
  290. } catch (e) {
  291. Logger.error(e);
  292. }
  293. }
  294. void _onError(Object error) {
  295. Logger.error('返回的错误: $error');
  296. }
  297. void showAlert(String text, BuildContext context) {
  298. showDialog(
  299. context: context,
  300. builder: (BuildContext context) =>
  301. CupertinoAlertDialog(title: new Text("提示"), content: new Text(text), actions: <Widget>[
  302. new FlatButton(
  303. child: new Text("OK"),
  304. onPressed: () {
  305. Navigator.of(context).pop();
  306. },
  307. )
  308. ]));
  309. }
  310. }