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

341 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. ///初始化一些数据
  50. initAsync();
  51. super.initState();
  52. }
  53. ///初始化各种监听
  54. initAsync() async {
  55. try {
  56. WidgetsBinding.instance.addObserver(this);
  57. ///渲染完第一帧后调用
  58. WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
  59. Timer(Duration(milliseconds: 500), (){
  60. NativeUtil.notifyInitSuccess();
  61. });
  62. });
  63. String data = BaseSettingModel.setting.tab['data'];
  64. try {
  65. List list = convert.jsonDecode(data);
  66. _data = list.map((item) {
  67. return Map<String, dynamic>.from(item);
  68. }).toList();
  69. Logger.debug(_data);
  70. } catch (error) {
  71. Logger.error(error);
  72. }
  73. Constants.isShowIntellectDialog = false;
  74. TaobaoAuth.initAuth(context);
  75. //弹窗
  76. _showPolicy();
  77. Moblink.uploadPrivacyPermissionStatus(1, (bool success) {});
  78. SharesdkPlugin.uploadPrivacyPermissionStatus(1, (bool success) {});
  79. // 是安卓系统,Android场景还原的实现
  80. /*if (defaultTargetPlatform == TargetPlatform.android) {
  81. }*/
  82. //app后台杀死时候的还原
  83. Moblink.restoreScene(_restore);
  84. // 监听开始(传递监听到原生端,用户监听场景还原的数据回传回来)
  85. _eventChannel.receiveBroadcastStream().listen(_onEvent, onError: _onError);
  86. MobPushUtil.addPushReceiver();
  87. EventUtil.instance.on<LoginSuccessEvent>().listen((event) async {
  88. UserInfoModel userInfo = UserInfoNotifier?.staitcUserInfo;
  89. var setting = await NativeUtil.getSetting();
  90. String masterId = setting['master_id'];
  91. Logger.log("我的Alias: " + masterId + "_" + userInfo?.userId);
  92. if (!EmptyUtil.isEmpty(userInfo.userId) && !EmptyUtil.isEmpty(masterId)) {
  93. MobPushUtil.setAlias(masterId + "_" + userInfo.userId);
  94. }
  95. });
  96. EventUtil.instance.on<LogOut>().listen((event) {
  97. MobPushUtil.deleteAlias();
  98. });
  99. super.initState();
  100. MobPushUtil.addPushReceiver();
  101. EventUtil.instance.on<LoginSuccessEvent>().listen((event) async {
  102. UserInfoModel userInfo = UserInfoNotifier?.staitcUserInfo;
  103. var setting = await NativeUtil.getSetting();
  104. String masterId = setting['master_id'];
  105. Logger.log("我的Alias: " + masterId + "_" + userInfo?.userId);
  106. if (!EmptyUtil.isEmpty(userInfo.userId) && !EmptyUtil.isEmpty(masterId)) {
  107. MobPushUtil.setAlias(masterId + "_" + userInfo.userId);
  108. }
  109. });
  110. EventUtil.instance.on<LogOut>().listen((event) {
  111. MobPushUtil.deleteAlias();
  112. });
  113. } catch (e, s) {
  114. print(e);
  115. print(s);
  116. }
  117. }
  118. @override
  119. void dispose() {
  120. WidgetsBinding.instance.removeObserver(this);
  121. super.dispose();
  122. }
  123. @override
  124. void didChangeAppLifecycleState(AppLifecycleState state) {
  125. ///智能粘贴板
  126. IntellectCreate.checkAndCreate(state, context);
  127. super.didChangeAppLifecycleState(state);
  128. }
  129. @override
  130. Widget build(BuildContext context) {
  131. ScreenUtil.init(context, width: 750, height: 1334);
  132. Logger.debug('home_page build');
  133. List<Map<String, dynamic>> tabs = _data;
  134. if (tabs == null || tabs.length == 0) {
  135. return Scaffold();
  136. }
  137. for (int i = 0; i < tabs.length;) {
  138. if (tabs[i]['is_show'] != "1") {
  139. tabs.removeAt(i);
  140. } else {
  141. i++;
  142. }
  143. }
  144. List<Widget> contentWidgets = tabs.map((item) {
  145. BaseTabModel model = BaseTabModel.fromJson(item);
  146. return PageFactory.create(model.skipIdentifier, item);
  147. }).toList();
  148. if (_currentIndex >= contentWidgets.length) {
  149. _currentIndex = 0;
  150. }
  151. return Scaffold(
  152. body: IndexedStack(
  153. index: _currentIndex,
  154. children: contentWidgets,
  155. ),
  156. //底部导航栏
  157. bottomNavigationBar: createBottomNavigationBar(tabs),
  158. );
  159. }
  160. Widget createBottomNavigationBar(List<Map<String, dynamic>> tabs) {
  161. List<BottomNavigationBarItem> items = List<BottomNavigationBarItem>();
  162. for (int i = 0; i < tabs.length; i++) {
  163. BaseTabModel model = BaseTabModel.fromJson(tabs[i]);
  164. String icon = ImageUtil.getUrl(model.icon);
  165. String selectedIcon = ImageUtil.getUrl(model.chooseIcon ?? model.icon);
  166. String textColor = model.fontColor;
  167. String chooseColor = model.chooseColor ?? textColor;
  168. if (model.isShow == "1") {
  169. items.add(BottomNavigationBarItem(
  170. icon: Container(
  171. width: 24,
  172. height: 24,
  173. margin: EdgeInsets.only(bottom: 4),
  174. child: CachedNetworkImage(
  175. imageUrl: _currentIndex == i ? selectedIcon : icon,
  176. fit: BoxFit.fitWidth,
  177. ),
  178. ),
  179. title: Text(
  180. model.name,
  181. style: TextStyle(fontSize: 11, color: HexColor.fromHex(_currentIndex == i ? chooseColor : textColor)),
  182. )));
  183. }
  184. }
  185. if (items.length < 2) {
  186. return Container();
  187. }
  188. String bgColor = '#ffffff';
  189. if (tabs.first != null) {
  190. BaseTabModel model = BaseTabModel.fromJson(tabs.first);
  191. bgColor = model.bgColor ?? bgColor;
  192. }
  193. return BottomNavigationBar(
  194. backgroundColor: HexColor.fromHex(bgColor),
  195. type: BottomNavigationBarType.fixed,
  196. selectedFontSize: 11,
  197. unselectedFontSize: 11,
  198. currentIndex: _currentIndex,
  199. elevation: 0,
  200. onTap: ((index) async {
  201. BaseTabModel model = BaseTabModel.fromJson(tabs[index]);
  202. if (await _checkLimit(model)) {
  203. ///避免同一个页面多次点击多次重绘
  204. if (_currentIndex == index) {
  205. return;
  206. } else {
  207. setState(() {
  208. _currentIndex = index;
  209. });
  210. }
  211. }
  212. }),
  213. //底部导航栏
  214. items: items);
  215. }
  216. Future<bool> _checkLimit(BaseTabModel model) async {
  217. if (model.requiredLogin == '1') {
  218. UserInfoModel user = await Provider.of<UserInfoNotifier>(context, listen: false).getUserInfoModel();
  219. print(user.toString());
  220. if (user?.token == null || user.token == '') {
  221. print('need login...');
  222. RouterUtil.goLogin(context);
  223. return false;
  224. }
  225. }
  226. return true;
  227. }
  228. ///
  229. /// 各种弹窗
  230. /// 1、用户协议弹窗 搬到启动页之前显示了
  231. /// 2、通知栏开启弹窗
  232. /// 3、活动弹窗
  233. ///
  234. Future _showPolicy() async {
  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) =>
  294. CupertinoAlertDialog(title: new Text("提示"), content: new Text(text), actions: <Widget>[
  295. new FlatButton(
  296. child: new Text("OK"),
  297. onPressed: () {
  298. Navigator.of(context).pop();
  299. },
  300. )
  301. ]));
  302. }
  303. }