基础组件库
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 16 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
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514
  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 LifeState<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. // 通知弹窗
  323. String isShowNotiPermission = await SharedPreferencesUtil.getStringValue(Constants.isShowNotiPermission);
  324. if (isShowNotiPermission == null || isShowNotiPermission != '1') {
  325. await NotificationSettingDialog.show(context);
  326. await SharedPreferencesUtil.setStringValue(Constants.isShowNotiPermission, "1");
  327. }
  328. // 活动弹窗
  329. await AdvertisingDialog.show(context);
  330. if (!await Permission.storage.isGranted) {
  331. var result = await showDialog(
  332. context: context,
  333. child: TipDialog(
  334. content: "为了节省网络流量,我们需要获取本地存储权限,缓存信息数据。",
  335. ));
  336. if (result != null && result) {
  337. await Permission.storage.request();
  338. // 初始化百川sdk
  339. FlutterAlibc.initAlibc(version: "", appName: "").then((result) async {
  340. Logger.debug('初始化百川sdk ${result.errorCode} ${result.errorMessage}');
  341. });
  342. }
  343. }
  344. await Future.delayed(Duration(milliseconds: 600), () async {
  345. //debug app不更新 app更新插件
  346. await AppUpdateUtil.initXUpdate();
  347. // 检查app更新
  348. await AppUpdateUtil.updateApp(context);
  349. });
  350. IntellectCreate.checkAndCreateFirst(context);
  351. }
  352. // 场景还原,记录邀请码
  353. void _restore(MLSDKScene scene) {
  354. // const bool inProduction = const bool.fromEnvironment("dart.vm.product");
  355. // if (!inProduction) {
  356. // // 非release环境,弹窗测试
  357. // showAlert('要还原的路径为:' + scene.className + '\n' + scene.params.toString(),
  358. // context);
  359. // }
  360. Logger.debug('要还原的路径为:' + scene.className);
  361. try {
  362. Map<String, dynamic> params = Map<String, dynamic>.from(scene.params);
  363. if (params.containsKey('tgid')) {
  364. String tgid = params['tgid'].toString();
  365. // 记录邀请码到本地
  366. MobUtil.storeInvitedCode(tgid);
  367. }
  368. } catch (e) {
  369. Logger.error(e);
  370. }
  371. }
  372. //app存在后台时候的还原
  373. void _onEvent(Object event) {
  374. Logger.debug('返回的内容: $event');
  375. try {
  376. if (null != event) {
  377. Map<String, dynamic> params = Map<String, dynamic>.from(event);
  378. // const bool inProduction = const bool.fromEnvironment("dart.vm.product");
  379. // if (!inProduction) {
  380. // // 非release环境,弹窗测试
  381. // showAlert('要还原的路径为[活着]:$event', context);
  382. // }
  383. if (params['params'].containsKey('tgid')) {
  384. String tgid = params['params']['tgid'].toString();
  385. // 记录邀请码到本地
  386. MobUtil.storeInvitedCode(tgid);
  387. }
  388. }
  389. } catch (e) {
  390. Logger.error(e);
  391. }
  392. }
  393. void _onError(Object error) {
  394. Logger.error('返回的错误: $error');
  395. }
  396. void showAlert(String text, BuildContext context) {
  397. showDialog(
  398. context: context,
  399. builder: (BuildContext context) => CupertinoAlertDialog(title: new Text("提示"), content: new Text(text), actions: <Widget>[
  400. new FlatButton(
  401. child: new Text("OK"),
  402. onPressed: () {
  403. Navigator.of(context).pop();
  404. },
  405. )
  406. ]));
  407. }
  408. @override
  409. void onPaused() {
  410. print("首页调用不可见");
  411. IntellectCreate.setCheck(false);
  412. }
  413. @override
  414. void onResume() {
  415. print("首页调用可见");
  416. IntellectCreate.setCheck(true);
  417. }
  418. @override
  419. // TODO: implement wantKeepAlive
  420. bool get wantKeepAlive => true;
  421. }
  422. final RouteObserver<Route> lifeObserver = RouteObserver();
  423. abstract class LifeState<T extends StatefulWidget> extends State<T> with RouteAware {
  424. @override
  425. void initState() {
  426. super.initState();
  427. }
  428. @override
  429. void didChangeDependencies() {
  430. lifeObserver.subscribe(this, ModalRoute.of(context));
  431. super.didChangeDependencies();
  432. }
  433. @override
  434. void dispose() {
  435. lifeObserver.unsubscribe(this);
  436. super.dispose();
  437. }
  438. void didPop() {
  439. onPaused();
  440. }
  441. void didPopNext() {
  442. onResume();
  443. print("回到首页");
  444. setState(() {});
  445. }
  446. void didPush() {
  447. onResume();
  448. }
  449. void didPushNext() {
  450. onPaused();
  451. }
  452. void onResume();
  453. void onPaused();
  454. }