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

488 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 {
  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. Widget build(BuildContext context) {
  157. ScreenUtil.init(context, width: 750, height: 1334);
  158. Logger.debug('home_page build');
  159. List<Map<String, dynamic>> tabs = _data;
  160. if (tabs == null || tabs.length == 0) {
  161. return Scaffold();
  162. }
  163. for (int i = 0; i < tabs.length;) {
  164. if (tabs[i]['is_show'] != "1") {
  165. tabs.removeAt(i);
  166. } else {
  167. i++;
  168. }
  169. }
  170. List<Widget> contentWidgets = tabs.map((item) {
  171. BaseTabModel model = BaseTabModel.fromJson(item);
  172. return PageFactory.create(model.skipIdentifier, item);
  173. }).toList();
  174. if (_currentIndex >= contentWidgets.length) {
  175. _currentIndex = 0;
  176. }
  177. return Scaffold(
  178. body: IndexedStack(
  179. index: _currentIndex,
  180. children: contentWidgets,
  181. ),
  182. //底部导航栏
  183. bottomNavigationBar: createBottomNavigationBar(tabs),
  184. );
  185. }
  186. Widget createBottomNavigationBar(List<Map<String, dynamic>> tabs) {
  187. List<BottomNavigationBarItem> items = List<BottomNavigationBarItem>();
  188. for (int i = 0; i < tabs.length; i++) {
  189. BaseTabModel model = BaseTabModel.fromJson(tabs[i]);
  190. String icon = ImageUtil.getUrl(model.icon);
  191. String selectedIcon = ImageUtil.getUrl(model.chooseIcon ?? model.icon);
  192. String textColor = model.fontColor;
  193. String chooseColor = model.chooseColor ?? textColor;
  194. if (model.isShow == "1") {
  195. items.add(BottomNavigationBarItem(
  196. icon: Container(
  197. width: 24,
  198. height: 24,
  199. margin: EdgeInsets.only(bottom: 4),
  200. child: CachedNetworkImage(
  201. imageUrl: _currentIndex == i ? selectedIcon : icon,
  202. fit: BoxFit.fitWidth,
  203. ),
  204. ),
  205. title: Text(
  206. model.name,
  207. style: TextStyle(fontSize: 11, color: HexColor.fromHex(_currentIndex == i ? chooseColor : textColor)),
  208. )));
  209. }
  210. }
  211. if (items.length < 2) {
  212. return Container();
  213. }
  214. String bgColor = '#ffffff';
  215. if (tabs.first != null) {
  216. BaseTabModel model = BaseTabModel.fromJson(tabs.first);
  217. bgColor = model.bgColor ?? bgColor;
  218. }
  219. return BottomNavigationBar(
  220. backgroundColor: HexColor.fromHex(bgColor),
  221. type: BottomNavigationBarType.fixed,
  222. selectedFontSize: 11,
  223. unselectedFontSize: 11,
  224. currentIndex: _currentIndex,
  225. elevation: 0,
  226. onTap: ((index) async {
  227. BaseTabModel model = BaseTabModel.fromJson(tabs[index]);
  228. if (await _checkLimit(model)) {
  229. ///避免同一个页面多次点击多次重绘
  230. if (_currentIndex == index) {
  231. return;
  232. } else {
  233. setState(() {
  234. _currentIndex = index;
  235. });
  236. }
  237. }
  238. }),
  239. //底部导航栏
  240. items: items);
  241. }
  242. // Widget createBottomNavigationBarNew(List<Map<String, dynamic>> tabs) {
  243. //
  244. // List<TabItem> items = List<TabItem>();
  245. // for (int i = 0; i < tabs.length; i++) {
  246. // BaseTabModel model = BaseTabModel.fromJson(tabs[i]);
  247. // String icon = ImageUtil.getUrl(model.icon);
  248. // String selectedIcon = ImageUtil.getUrl(model.chooseIcon ?? model.icon);
  249. // String textColor = model.fontColor;
  250. // String chooseColor = model.chooseColor ?? textColor;
  251. //
  252. // if (model.isShow == "1") {
  253. // items.add(TabItem<Image>(
  254. // icon: Image.network(icon ?? ''),
  255. // activeIcon: Image.network(selectedIcon ?? ''),
  256. // title: model.name ?? ''
  257. // ));
  258. // }
  259. // }
  260. //
  261. // if (items.length < 2) {
  262. // return Container();
  263. // }
  264. // String bgColor = '#ffffff';
  265. // String textColor = '#999999';
  266. // String activeColor = '#FF4242';
  267. // if (tabs.first != null) {
  268. // BaseTabModel model = BaseTabModel.fromJson(tabs.first);
  269. // bgColor = model.bgColor ?? bgColor;
  270. // textColor = model?.fontColor ?? textColor;
  271. // activeColor = model?.chooseColor ?? activeColor;
  272. // }
  273. //
  274. // return ConvexAppBar(
  275. // elevation: 0,
  276. // backgroundColor: HexColor.fromHex(bgColor),
  277. // items: items,
  278. // height: 50,
  279. // color: HexColor.fromHex(textColor),
  280. // activeColor: HexColor.fromHex(activeColor),
  281. // initialActiveIndex: _currentIndex,
  282. // style: TabStyle.react,
  283. // onTap: (int index) async {
  284. // BaseTabModel model = BaseTabModel.fromJson(tabs[index]);
  285. // if (await _checkLimit(model)) {
  286. // ///避免同一个页面多次点击多次重绘
  287. // if (_currentIndex == index) {
  288. // return;
  289. // } else {
  290. // setState(() {
  291. // _currentIndex = index;
  292. // });
  293. // }
  294. // }
  295. // },
  296. // );
  297. // }
  298. Future<bool> _checkLimit(BaseTabModel model) async {
  299. if (model.requiredLogin == '1') {
  300. UserInfoModel user = await Provider.of<UserInfoNotifier>(context, listen: false).getUserInfoModel();
  301. print(user.toString());
  302. if (user?.token == null || user.token == '') {
  303. print('need login...');
  304. RouterUtil.goLogin(context);
  305. return false;
  306. }
  307. }
  308. return true;
  309. }
  310. ///
  311. /// 各种弹窗
  312. /// 1、用户协议弹窗 搬到启动页之前显示了
  313. /// 2、通知栏开启弹窗
  314. /// 3、活动弹窗
  315. ///
  316. Future _showPolicy() async {
  317. // 通知弹窗
  318. String isShowNotiPermission = await SharedPreferencesUtil.getStringValue(Constants.isShowNotiPermission);
  319. if (isShowNotiPermission == null || isShowNotiPermission != '1') {
  320. await NotificationSettingDialog.show(context);
  321. await SharedPreferencesUtil.setStringValue(Constants.isShowNotiPermission, "1");
  322. }
  323. // 活动弹窗
  324. await AdvertisingDialog.show(context);
  325. // 检查app更新
  326. await AppUpdateUtil.updateApp(context);
  327. IntellectCreate.checkAndCreateFirst(context);
  328. }
  329. // 场景还原,记录邀请码
  330. void _restore(MLSDKScene scene) {
  331. // const bool inProduction = const bool.fromEnvironment("dart.vm.product");
  332. // if (!inProduction) {
  333. // // 非release环境,弹窗测试
  334. // showAlert('要还原的路径为:' + scene.className + '\n' + scene.params.toString(),
  335. // context);
  336. // }
  337. Logger.debug('要还原的路径为:' + scene.className);
  338. try {
  339. Map<String, dynamic> params = Map<String, dynamic>.from(scene.params);
  340. if (params.containsKey('tgid')) {
  341. String tgid = params['tgid'].toString();
  342. // 记录邀请码到本地
  343. MobUtil.storeInvitedCode(tgid);
  344. }
  345. } catch (e) {
  346. Logger.error(e);
  347. }
  348. }
  349. //app存在后台时候的还原
  350. void _onEvent(Object event) {
  351. Logger.debug('返回的内容: $event');
  352. try {
  353. if (null != event) {
  354. Map<String, dynamic> params = Map<String, dynamic>.from(event);
  355. // const bool inProduction = const bool.fromEnvironment("dart.vm.product");
  356. // if (!inProduction) {
  357. // // 非release环境,弹窗测试
  358. // showAlert('要还原的路径为[活着]:$event', context);
  359. // }
  360. if (params['params'].containsKey('tgid')) {
  361. String tgid = params['params']['tgid'].toString();
  362. // 记录邀请码到本地
  363. MobUtil.storeInvitedCode(tgid);
  364. }
  365. }
  366. } catch (e) {
  367. Logger.error(e);
  368. }
  369. }
  370. void _onError(Object error) {
  371. Logger.error('返回的错误: $error');
  372. }
  373. void showAlert(String text, BuildContext context) {
  374. showDialog(
  375. context: context,
  376. builder: (BuildContext context) => CupertinoAlertDialog(title: new Text("提示"), content: new Text(text), actions: <Widget>[
  377. new FlatButton(
  378. child: new Text("OK"),
  379. onPressed: () {
  380. Navigator.of(context).pop();
  381. },
  382. )
  383. ]));
  384. }
  385. @override
  386. void onPaused() {
  387. print("首页调用不可见");
  388. IntellectCreate.setCheck(false);
  389. }
  390. @override
  391. void onResume() {
  392. print("首页调用可见");
  393. IntellectCreate.setCheck(true);
  394. }
  395. }
  396. final RouteObserver<Route> lifeObserver = RouteObserver();
  397. abstract class LifeState<T extends StatefulWidget> extends State<T>
  398. with RouteAware {
  399. @override
  400. void initState() {
  401. super.initState();
  402. }
  403. @override
  404. void didChangeDependencies() {
  405. lifeObserver.subscribe(this, ModalRoute.of(context));
  406. super.didChangeDependencies();
  407. }
  408. @override
  409. void dispose() {
  410. lifeObserver.unsubscribe(this);
  411. super.dispose();
  412. }
  413. void didPop() {
  414. onPaused();
  415. }
  416. void didPopNext() {
  417. onResume();
  418. }
  419. void didPush() {
  420. onResume();
  421. }
  422. void didPushNext() {
  423. onPaused();
  424. }
  425. void onResume();
  426. void onPaused();
  427. }