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

home_page.dart 12 KiB

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