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

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