基础组件库
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。

home_page.dart 15 KiB

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