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

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