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

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