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

499 lines
15 KiB

  1. import 'dart:async';
  2. import 'dart:convert' as convert;
  3. import 'package:cached_network_image/cached_network_image.dart';
  4. import 'package:flutter/cupertino.dart';
  5. import 'package:flutter/foundation.dart';
  6. import 'package:flutter/material.dart';
  7. import 'package:flutter/services.dart';
  8. import 'package:flutter/widgets.dart';
  9. import 'package:moblink/moblink.dart';
  10. import 'package:provider/provider.dart';
  11. import 'package:zhiying_base_widget/dialog/global_dialog/advertising_dialog/advertising_dialog.dart';
  12. import 'package:zhiying_base_widget/dialog/global_dialog/intellect_search_goods_dialog/intellect_create.dart';
  13. import 'package:zhiying_base_widget/dialog/global_dialog/notification_setting_dialog/notification_setting_dialog.dart';
  14. import 'package:zhiying_base_widget/models/app_config_model.dart';
  15. import 'package:zhiying_base_widget/pages/custom_page/event/reload_event.dart';
  16. import 'package:zhiying_base_widget/utils/contants.dart';
  17. import 'package:zhiying_base_widget/utils/mob_push_util.dart';
  18. import 'package:zhiying_base_widget/widgets/restart_widget/restart_widget.dart';
  19. import 'package:zhiying_comm/models/base/base_tab_model.dart';
  20. import 'package:zhiying_comm/util/image_util.dart';
  21. import 'package:zhiying_comm/util/mob_util/mob_util.dart';
  22. import 'package:sharesdk_plugin/sharesdk_plugin.dart';
  23. import 'package:zhiying_comm/util/shared_prefe_util.dart';
  24. import 'package:zhiying_comm/util/update/app_update_util.dart';
  25. import 'package:zhiying_comm/zhiying_comm.dart';
  26. import 'package:zhiying_comm/util/event_util/login_success_event.dart';
  27. import 'package:zhiying_comm/util/event_util/event_util.dart';
  28. import 'package:zhiying_comm/util/event_util/log_out.dart';
  29. import '../../models/app_config_model.dart';
  30. class HomeCenterPage extends StatefulWidget {
  31. @override
  32. _HomeCenterPageState createState() => _HomeCenterPageState();
  33. }
  34. class _HomeCenterPageState extends State<HomeCenterPage> {
  35. @override
  36. Widget build(BuildContext context) {
  37. return RestartWidget(child: HomePage());
  38. }
  39. }
  40. class HomePage extends StatefulWidget {
  41. HomePage({Key key}) : super(key: key);
  42. @override
  43. _HomePageState createState() => _HomePageState();
  44. }
  45. class _HomePageState extends LifeState<HomePage> with WidgetsBindingObserver, TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  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. StreamSubscription reloadSubscription;
  51. StreamSubscription aliasSubscription;
  52. StreamSubscription logOutSubscription;
  53. StreamSubscription loginSubscription;
  54. StreamSubscription eventChannelSubscription;
  55. @override
  56. void initState() {
  57. ///初始化一些数据
  58. initAsync();
  59. //如果登出则重新打开首页
  60. streamSubscription = EventUtil.instance.on<LogOut>().listen((event) async {
  61. UserInfoModel user = await Provider.of<UserInfoNotifier>(context, listen: false).getUserInfoModel();
  62. user.token = '';
  63. Navigator.maybePop(context);
  64. print("重启1");
  65. Navigator.pushReplacementNamed(context, "/homePage");
  66. });
  67. reloadSubscription = EventUtil.instance.on<ReloadEvent>().listen((event) async {
  68. print("重启2");
  69. await BaseSettingModel.init(isGetCache: false);
  70. RestartWidget.restartApp(context);
  71. });
  72. super.initState();
  73. }
  74. ///初始化各种监听
  75. initAsync() async {
  76. try {
  77. WidgetsBinding.instance.addObserver(this);
  78. ///渲染完第一帧后调用
  79. WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
  80. int delay = ((num.tryParse(AppConfigModel.appStartDelay) ?? 0.5) * 1000).toInt();
  81. print("延时" + AppConfigModel.appStartDelay.toString());
  82. Timer(Duration(milliseconds: delay), () {
  83. NativeUtil.notifyInitSuccess();
  84. });
  85. });
  86. initBaseSet();
  87. Constants.isShowIntellectDialog = false;
  88. TaobaoAuth.initAuth(context);
  89. //弹窗
  90. _showPolicy();
  91. Moblink.uploadPrivacyPermissionStatus(1, (bool success) {});
  92. SharesdkPlugin.uploadPrivacyPermissionStatus(1, (bool success) {});
  93. // 是安卓系统,Android场景还原的实现
  94. /*if (defaultTargetPlatform == TargetPlatform.android) {
  95. }*/
  96. //app后台杀死时候的还原
  97. Moblink.restoreScene(_restore);
  98. // 监听开始(传递监听到原生端,用户监听场景还原的数据回传回来)
  99. eventChannelSubscription = _eventChannel.receiveBroadcastStream().listen(_onEvent, onError: _onError);
  100. MobPushUtil.addPushReceiver();
  101. aliasSubscription = 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. logOutSubscription = EventUtil.instance.on<LogOut>().listen((event) {
  111. MobPushUtil.deleteAlias();
  112. });
  113. MobPushUtil.addPushReceiver();
  114. loginSubscription = 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. } catch (e, s) {
  124. print(e);
  125. print(s);
  126. }
  127. }
  128. initBaseSet() {
  129. String data = BaseSettingModel.setting.tab['data'];
  130. try {
  131. List list = convert.jsonDecode(data);
  132. _data = list.map((item) {
  133. return Map<String, dynamic>.from(item);
  134. }).toList();
  135. Logger.debug(_data);
  136. } catch (error) {
  137. Logger.error(error);
  138. }
  139. }
  140. @override
  141. void dispose() {
  142. WidgetsBinding.instance.removeObserver(this);
  143. streamSubscription.cancel();
  144. reloadSubscription?.cancel();
  145. aliasSubscription?.cancel();
  146. logOutSubscription?.cancel();
  147. loginSubscription?.cancel();
  148. eventChannelSubscription?.cancel();
  149. super.dispose();
  150. }
  151. @override
  152. void didChangeAppLifecycleState(AppLifecycleState state) {
  153. ///智能粘贴板
  154. IntellectCreate.checkAndCreate(state, context);
  155. super.didChangeAppLifecycleState(state);
  156. }
  157. @override
  158. Widget build(BuildContext context) {
  159. ScreenUtil.init(context, width: 750, height: 1334);
  160. Logger.debug('home_page build');
  161. List<Map<String, dynamic>> tabs = _data;
  162. if (tabs == null || tabs.length == 0) {
  163. return Scaffold();
  164. }
  165. for (int i = 0; i < tabs.length;) {
  166. if (tabs[i]['is_show'] != "1") {
  167. tabs.removeAt(i);
  168. } else {
  169. i++;
  170. }
  171. }
  172. List<Widget> contentWidgets = tabs.map((item) {
  173. BaseTabModel model = BaseTabModel.fromJson(item);
  174. return PageFactory.create(model.skipIdentifier, item);
  175. }).toList();
  176. if (_currentIndex >= contentWidgets.length) {
  177. _currentIndex = 0;
  178. }
  179. return Scaffold(
  180. body: IndexedStack(
  181. index: _currentIndex,
  182. children: contentWidgets,
  183. ),
  184. //底部导航栏
  185. bottomNavigationBar: createBottomNavigationBar(tabs),
  186. );
  187. }
  188. Widget createBottomNavigationBar(List<Map<String, dynamic>> tabs) {
  189. List<BottomNavigationBarItem> items = List<BottomNavigationBarItem>();
  190. for (int i = 0; i < tabs.length; i++) {
  191. BaseTabModel model = BaseTabModel.fromJson(tabs[i]);
  192. String icon = ImageUtil.getUrl(model.icon);
  193. String selectedIcon = ImageUtil.getUrl(model.chooseIcon ?? model.icon);
  194. String textColor = model.fontColor;
  195. String chooseColor = model.chooseColor ?? textColor;
  196. if (model.isShow == "1") {
  197. items.add(BottomNavigationBarItem(
  198. icon: Container(
  199. width: 24,
  200. height: 24,
  201. margin: EdgeInsets.only(bottom: 4),
  202. child: CachedNetworkImage(
  203. imageUrl: _currentIndex == i ? selectedIcon : icon,
  204. fit: BoxFit.fitWidth,
  205. ),
  206. ),
  207. title: Text(
  208. model.name,
  209. style: TextStyle(fontSize: 11, color: HexColor.fromHex(_currentIndex == i ? chooseColor : textColor)),
  210. )));
  211. }
  212. }
  213. if (items.length < 2) {
  214. return Container();
  215. }
  216. String bgColor = '#ffffff';
  217. if (tabs.first != null) {
  218. BaseTabModel model = BaseTabModel.fromJson(tabs.first);
  219. bgColor = model.bgColor ?? bgColor;
  220. }
  221. return BottomNavigationBar(
  222. backgroundColor: HexColor.fromHex(bgColor),
  223. type: BottomNavigationBarType.fixed,
  224. selectedFontSize: 11,
  225. unselectedFontSize: 11,
  226. currentIndex: _currentIndex,
  227. elevation: 0,
  228. onTap: ((index) async {
  229. BaseTabModel model = BaseTabModel.fromJson(tabs[index]);
  230. if (await _checkLimit(model)) {
  231. ///避免同一个页面多次点击多次重绘
  232. if (_currentIndex == index) {
  233. return;
  234. } else {
  235. setState(() {
  236. _currentIndex = index;
  237. });
  238. }
  239. }
  240. }),
  241. //底部导航栏
  242. items: items);
  243. }
  244. // Widget createBottomNavigationBarNew(List<Map<String, dynamic>> tabs) {
  245. //
  246. // List<TabItem> items = List<TabItem>();
  247. // for (int i = 0; i < tabs.length; i++) {
  248. // BaseTabModel model = BaseTabModel.fromJson(tabs[i]);
  249. // String icon = ImageUtil.getUrl(model.icon);
  250. // String selectedIcon = ImageUtil.getUrl(model.chooseIcon ?? model.icon);
  251. // String textColor = model.fontColor;
  252. // String chooseColor = model.chooseColor ?? textColor;
  253. //
  254. // if (model.isShow == "1") {
  255. // items.add(TabItem<Image>(
  256. // icon: Image.network(icon ?? ''),
  257. // activeIcon: Image.network(selectedIcon ?? ''),
  258. // title: model.name ?? ''
  259. // ));
  260. // }
  261. // }
  262. //
  263. // if (items.length < 2) {
  264. // return Container();
  265. // }
  266. // String bgColor = '#ffffff';
  267. // String textColor = '#999999';
  268. // String activeColor = '#FF4242';
  269. // if (tabs.first != null) {
  270. // BaseTabModel model = BaseTabModel.fromJson(tabs.first);
  271. // bgColor = model.bgColor ?? bgColor;
  272. // textColor = model?.fontColor ?? textColor;
  273. // activeColor = model?.chooseColor ?? activeColor;
  274. // }
  275. //
  276. // return ConvexAppBar(
  277. // elevation: 0,
  278. // backgroundColor: HexColor.fromHex(bgColor),
  279. // items: items,
  280. // height: 50,
  281. // color: HexColor.fromHex(textColor),
  282. // activeColor: HexColor.fromHex(activeColor),
  283. // initialActiveIndex: _currentIndex,
  284. // style: TabStyle.react,
  285. // onTap: (int index) async {
  286. // BaseTabModel model = BaseTabModel.fromJson(tabs[index]);
  287. // if (await _checkLimit(model)) {
  288. // ///避免同一个页面多次点击多次重绘
  289. // if (_currentIndex == index) {
  290. // return;
  291. // } else {
  292. // setState(() {
  293. // _currentIndex = index;
  294. // });
  295. // }
  296. // }
  297. // },
  298. // );
  299. // }
  300. Future<bool> _checkLimit(BaseTabModel model) async {
  301. if (model.requiredLogin == '1') {
  302. UserInfoModel user = await Provider.of<UserInfoNotifier>(context, listen: false).getUserInfoModel();
  303. print(user.toString());
  304. if (user?.token == null || user.token == '') {
  305. print('need login...');
  306. RouterUtil.goLogin(context);
  307. return false;
  308. }
  309. }
  310. return true;
  311. }
  312. ///
  313. /// 各种弹窗
  314. /// 1、用户协议弹窗 搬到启动页之前显示了
  315. /// 2、通知栏开启弹窗
  316. /// 3、活动弹窗
  317. ///
  318. Future _showPolicy() async {
  319. // 通知弹窗
  320. String isShowNotiPermission = await SharedPreferencesUtil.getStringValue(Constants.isShowNotiPermission);
  321. if (isShowNotiPermission == null || isShowNotiPermission != '1') {
  322. await NotificationSettingDialog.show(context);
  323. await SharedPreferencesUtil.setStringValue(Constants.isShowNotiPermission, "1");
  324. }
  325. // 活动弹窗
  326. await AdvertisingDialog.show(context);
  327. await Future.delayed(Duration(milliseconds: 600),() async {
  328. //debug app不更新 app更新插件
  329. await AppUpdateUtil.initXUpdate();
  330. // 检查app更新
  331. await AppUpdateUtil.updateApp(context);
  332. });
  333. IntellectCreate.checkAndCreateFirst(context);
  334. }
  335. // 场景还原,记录邀请码
  336. void _restore(MLSDKScene scene) {
  337. // const bool inProduction = const bool.fromEnvironment("dart.vm.product");
  338. // if (!inProduction) {
  339. // // 非release环境,弹窗测试
  340. // showAlert('要还原的路径为:' + scene.className + '\n' + scene.params.toString(),
  341. // context);
  342. // }
  343. Logger.debug('要还原的路径为:' + scene.className);
  344. try {
  345. Map<String, dynamic> params = Map<String, dynamic>.from(scene.params);
  346. if (params.containsKey('tgid')) {
  347. String tgid = params['tgid'].toString();
  348. // 记录邀请码到本地
  349. MobUtil.storeInvitedCode(tgid);
  350. }
  351. } catch (e) {
  352. Logger.error(e);
  353. }
  354. }
  355. //app存在后台时候的还原
  356. void _onEvent(Object event) {
  357. Logger.debug('返回的内容: $event');
  358. try {
  359. if (null != event) {
  360. Map<String, dynamic> params = Map<String, dynamic>.from(event);
  361. // const bool inProduction = const bool.fromEnvironment("dart.vm.product");
  362. // if (!inProduction) {
  363. // // 非release环境,弹窗测试
  364. // showAlert('要还原的路径为[活着]:$event', context);
  365. // }
  366. if (params['params'].containsKey('tgid')) {
  367. String tgid = params['params']['tgid'].toString();
  368. // 记录邀请码到本地
  369. MobUtil.storeInvitedCode(tgid);
  370. }
  371. }
  372. } catch (e) {
  373. Logger.error(e);
  374. }
  375. }
  376. void _onError(Object error) {
  377. Logger.error('返回的错误: $error');
  378. }
  379. void showAlert(String text, BuildContext context) {
  380. showDialog(
  381. context: context,
  382. builder: (BuildContext context) => CupertinoAlertDialog(title: new Text("提示"), content: new Text(text), actions: <Widget>[
  383. new FlatButton(
  384. child: new Text("OK"),
  385. onPressed: () {
  386. Navigator.of(context).pop();
  387. },
  388. )
  389. ]));
  390. }
  391. @override
  392. void onPaused() {
  393. print("首页调用不可见");
  394. IntellectCreate.setCheck(false);
  395. }
  396. @override
  397. void onResume() {
  398. print("首页调用可见");
  399. IntellectCreate.setCheck(true);
  400. }
  401. @override
  402. // TODO: implement wantKeepAlive
  403. bool get wantKeepAlive => true;
  404. }
  405. final RouteObserver<Route> lifeObserver = RouteObserver();
  406. abstract class LifeState<T extends StatefulWidget> extends State<T> with RouteAware {
  407. @override
  408. void initState() {
  409. super.initState();
  410. }
  411. @override
  412. void didChangeDependencies() {
  413. lifeObserver.subscribe(this, ModalRoute.of(context));
  414. super.didChangeDependencies();
  415. }
  416. @override
  417. void dispose() {
  418. lifeObserver.unsubscribe(this);
  419. super.dispose();
  420. }
  421. void didPop() {
  422. onPaused();
  423. }
  424. void didPopNext() {
  425. onResume();
  426. print("回到首页");
  427. setState(() {});
  428. }
  429. void didPush() {
  430. onResume();
  431. }
  432. void didPushNext() {
  433. onPaused();
  434. }
  435. void onResume();
  436. void onPaused();
  437. }