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