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

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