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

559 lines
18 KiB

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