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

570 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. print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Homepagedispose>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
  138. WidgetsBinding.instance.removeObserver(this);
  139. streamSubscription.cancel();
  140. reloadSubscription?.cancel();
  141. logOutSubscription?.cancel();
  142. loginSubscription?.cancel();
  143. eventChannelSubscription?.cancel();
  144. super.dispose();
  145. }
  146. @override
  147. void didChangeAppLifecycleState(AppLifecycleState state) {
  148. ///智能粘贴板
  149. IntellectCreate.checkAndCreate(state, context);
  150. super.didChangeAppLifecycleState(state);
  151. }
  152. @override
  153. Widget build(BuildContext context) {
  154. ScreenUtil.init(context, width: 750, height: 1334);
  155. Logger.debug('home_page build');
  156. List<Map<String, dynamic>> tabs = _data;
  157. if (tabs == null || tabs.length == 0) {
  158. return Scaffold();
  159. }
  160. for (int i = 0; i < tabs.length;) {
  161. if (tabs[i]['is_show'] != "1") {
  162. tabs.removeAt(i);
  163. } else {
  164. i++;
  165. }
  166. }
  167. List<Widget> contentWidgets = tabs.map((item) {
  168. BaseTabModel model = BaseTabModel.fromJson(item);
  169. //首页底部创建的item,把抖券判断置true
  170. item['is_bottom_video']=true;
  171. return PageFactory.create(model.skipIdentifier, item);
  172. }).toList();
  173. if (_currentIndex >= contentWidgets.length) {
  174. _currentIndex = 0;
  175. }
  176. return WillPopScope(
  177. onWillPop: () async{
  178. print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>HomepageBack>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
  179. EventUtil.instance.fire("HomepageSignOut");
  180. // 退出app
  181. // await SystemChannels.platform.invokeMethod('SystemNavigator.pop');
  182. return true;
  183. },
  184. child: Scaffold(
  185. body: IndexedStack(
  186. index: _currentIndex,
  187. children: contentWidgets,
  188. ),
  189. //底部导航栏
  190. bottomNavigationBar: createBottomNavigationBar(tabs),
  191. ),
  192. );
  193. }
  194. Widget createBottomNavigationBar(List<Map<String, dynamic>> tabs) {
  195. List<BottomNavigationBarItem> items = List<BottomNavigationBarItem>();
  196. for (int i = 0; i < tabs.length; i++) {
  197. BaseTabModel model = BaseTabModel.fromJson(tabs[i]);
  198. String icon = ImageUtil.getUrl(model.icon);
  199. String selectedIcon = ImageUtil.getUrl(model.chooseIcon ?? model.icon);
  200. String textColor = model.fontColor;
  201. String chooseColor = model.chooseColor ?? textColor;
  202. if (model.isShow == "1") {
  203. items.add(BottomNavigationBarItem(
  204. icon: Container(
  205. width: 24,
  206. height: 24,
  207. margin: EdgeInsets.only(bottom: 4),
  208. child: CachedNetworkImage(
  209. imageUrl: _currentIndex == i ? selectedIcon : icon,
  210. fit: BoxFit.fitWidth,
  211. ),
  212. ),
  213. title: Text(
  214. model.name,
  215. style: TextStyle(
  216. fontSize: 11,
  217. color: HexColor.fromHex(_currentIndex == i ? chooseColor : textColor)),
  218. )));
  219. }
  220. }
  221. if (items.length < 2) {
  222. return Container();
  223. }
  224. String bgColor = '#ffffff';
  225. if (tabs.first != null) {
  226. BaseTabModel model = BaseTabModel.fromJson(tabs.first);
  227. bgColor = model.bgColor ?? bgColor;
  228. }
  229. return BottomNavigationBar(
  230. backgroundColor: HexColor.fromHex(bgColor),
  231. type: BottomNavigationBarType.fixed,
  232. selectedFontSize: 11,
  233. unselectedFontSize: 11,
  234. currentIndex: _currentIndex,
  235. elevation: 0,
  236. onTap: ((index) async {
  237. BaseTabModel model = BaseTabModel.fromJson(tabs[index]);
  238. if (await _checkLimit(model)) {
  239. ///避免同一个页面多次点击多次重绘
  240. if (_currentIndex == index) {
  241. return;
  242. } else {
  243. /// 如果是外链,直接打开原生WebView
  244. if (model?.skipIdentifier == 'pub.flutter.url') {
  245. RouterUtil.openWebview(model?.url, context);
  246. return;
  247. }
  248. setState(() {
  249. _currentIndex = index;
  250. });
  251. EventUtil.instance.fire(model?.skipIdentifier);
  252. }
  253. }
  254. }),
  255. //底部导航栏
  256. items: items);
  257. }
  258. // Widget createBottomNavigationBarNew(List<Map<String, dynamic>> tabs) {
  259. //
  260. // List<TabItem> items = List<TabItem>();
  261. // for (int i = 0; i < tabs.length; i++) {
  262. // BaseTabModel model = BaseTabModel.fromJson(tabs[i]);
  263. // String icon = ImageUtil.getUrl(model.icon);
  264. // String selectedIcon = ImageUtil.getUrl(model.chooseIcon ?? model.icon);
  265. // String textColor = model.fontColor;
  266. // String chooseColor = model.chooseColor ?? textColor;
  267. //
  268. // if (model.isShow == "1") {
  269. // items.add(TabItem<Image>(
  270. // icon: Image.network(icon ?? ''),
  271. // activeIcon: Image.network(selectedIcon ?? ''),
  272. // title: model.name ?? ''
  273. // ));
  274. // }
  275. // }
  276. //
  277. // if (items.length < 2) {
  278. // return Container();
  279. // }
  280. // String bgColor = '#ffffff';
  281. // String textColor = '#999999';
  282. // String activeColor = '#FF4242';
  283. // if (tabs.first != null) {
  284. // BaseTabModel model = BaseTabModel.fromJson(tabs.first);
  285. // bgColor = model.bgColor ?? bgColor;
  286. // textColor = model?.fontColor ?? textColor;
  287. // activeColor = model?.chooseColor ?? activeColor;
  288. // }
  289. //
  290. // return ConvexAppBar(
  291. // elevation: 0,
  292. // backgroundColor: HexColor.fromHex(bgColor),
  293. // items: items,
  294. // height: 50,
  295. // color: HexColor.fromHex(textColor),
  296. // activeColor: HexColor.fromHex(activeColor),
  297. // initialActiveIndex: _currentIndex,
  298. // style: TabStyle.react,
  299. // onTap: (int index) async {
  300. // BaseTabModel model = BaseTabModel.fromJson(tabs[index]);
  301. // if (await _checkLimit(model)) {
  302. // ///避免同一个页面多次点击多次重绘
  303. // if (_currentIndex == index) {
  304. // return;
  305. // } else {
  306. // setState(() {
  307. // _currentIndex = index;
  308. // });
  309. // }
  310. // }
  311. // },
  312. // );
  313. // }
  314. Future<bool> _checkLimit(BaseTabModel model) async {
  315. if (model.requiredLogin == '1') {
  316. UserInfoModel user =
  317. await Provider.of<UserInfoNotifier>(context, listen: false).getUserInfoModel();
  318. print(user.toString());
  319. if (user?.token == null || user.token == '') {
  320. print('need login...');
  321. RouterUtil.goLogin(context);
  322. return false;
  323. }
  324. }
  325. return true;
  326. }
  327. ///
  328. /// 各种弹窗
  329. /// 1、用户协议弹窗 搬到启动页之前显示了
  330. /// 2、通知栏开启弹窗
  331. /// 3、活动弹窗
  332. ///
  333. Future _showPolicy() async {
  334. await Future.delayed(Duration(milliseconds: 1000), () async {
  335. // 通知弹窗
  336. ///每打开5次检查一次权限
  337. String showNotiPermissionTime = await SharedPreferencesUtil.getStringValue(
  338. Constants.showNotiPermissionTime,
  339. defaultVal: "5");
  340. int timer = int.tryParse(showNotiPermissionTime) ?? 0;
  341. if (timer % 5 == 0) {
  342. timer++;
  343. SharedPreferencesUtil.setStringValue(
  344. Constants.showNotiPermissionTime, timer.toString());
  345. if (!await Permission.storage.isGranted) {
  346. await NotificationSettingDialogNew.show(context);
  347. }
  348. String notificationAgree = await SharedPreferencesUtil.getStringValue(
  349. Constants.notificationAgree,
  350. defaultVal: "0");
  351. if (notificationAgree == "1" && await Permission.notification.isGranted) {
  352. ///啥也不干
  353. } else {
  354. if (notificationAgree == "0" || !await Permission.notification.isGranted) {
  355. bool isGranted = await Permission.notification.isGranted;
  356. var result = await showDialog(
  357. context: context,
  358. child: NotificationDialog(
  359. isGranted: isGranted,
  360. ));
  361. if (result != null && result) {
  362. SharedPreferencesUtil.setStringValue(Constants.notificationAgree, "1");
  363. if (!await Permission.notification.isGranted) {
  364. if (Platform.isIOS) {
  365. openAppSettings();
  366. } else {
  367. await NativeUtil.openAppSettings();
  368. }
  369. }
  370. }
  371. }
  372. }
  373. }
  374. // 活动弹窗
  375. await AdvertisingDialog.show(context);
  376. IntellectCreate.checkAndCreateFirst(context);
  377. });
  378. await Future.delayed(Duration(seconds: 3), () async {
  379. //debug app不更新 app更新插件
  380. await AppUpdateUtil.initXUpdate();
  381. // 检查app更新
  382. await AppUpdateUtil.updateApp(context);
  383. });
  384. }
  385. // 场景还原,记录邀请码
  386. void _restore(MLSDKScene scene) {
  387. // const bool inProduction = const bool.fromEnvironment("dart.vm.product");
  388. // if (!inProduction) {
  389. // // 非release环境,弹窗测试
  390. // showAlert('要还原的路径为:' + scene.className + '\n' + scene.params.toString(),
  391. // context);
  392. // }
  393. Logger.debug('要还原的路径为:' + scene.className);
  394. try {
  395. Map<String, dynamic> params = Map<String, dynamic>.from(scene.params);
  396. if (params.containsKey('tgid')) {
  397. String tgid = params['tgid'].toString();
  398. // 记录邀请码到本地
  399. MobUtil.storeInvitedCode(tgid);
  400. }
  401. } catch (e) {
  402. Logger.error(e);
  403. }
  404. }
  405. //app存在后台时候的还原
  406. void _onEvent(Object event) {
  407. Logger.debug('返回的内容: $event');
  408. try {
  409. if (null != event) {
  410. Map<String, dynamic> params = Map<String, dynamic>.from(event);
  411. // const bool inProduction = const bool.fromEnvironment("dart.vm.product");
  412. // if (!inProduction) {
  413. // // 非release环境,弹窗测试
  414. // showAlert('要还原的路径为[活着]:$event', context);
  415. // }
  416. if (params['params'].containsKey('tgid')) {
  417. String tgid = params['params']['tgid'].toString();
  418. // 记录邀请码到本地
  419. MobUtil.storeInvitedCode(tgid);
  420. }
  421. }
  422. } catch (e) {
  423. Logger.error(e);
  424. }
  425. }
  426. void _onError(Object error) {
  427. Logger.error('返回的错误: $error');
  428. }
  429. void showAlert(String text, BuildContext context) {
  430. showDialog(
  431. context: context,
  432. builder: (BuildContext context) => CupertinoAlertDialog(
  433. title: new Text("提示"),
  434. content: new Text(text),
  435. actions: <Widget>[
  436. new FlatButton(
  437. child: new Text("OK"),
  438. onPressed: () {
  439. Navigator.of(context).pop();
  440. },
  441. )
  442. ]));
  443. }
  444. @override
  445. void onPaused() {
  446. print("首页调用不可见");
  447. IntellectCreate.setCheck(false);
  448. }
  449. @override
  450. void onResume() {
  451. print("首页调用可见");
  452. IntellectCreate.setCheck(true);
  453. }
  454. @override
  455. // TODO: implement wantKeepAlive
  456. bool get wantKeepAlive => true;
  457. ///设置定向推送
  458. void setAlias() async {
  459. ///如果没有开启通知则设置别名
  460. if (await SharedPreferencesUtil.getStringValue(Constants.notificationAgree,
  461. defaultVal: "0") ==
  462. "1") {
  463. UserInfoModel userInfo = UserInfoNotifier?.staitcUserInfo;
  464. var setting = await NativeUtil.getSetting();
  465. String masterId = setting['master_id'];
  466. Logger.log("我的Alias: " + masterId + "_" + userInfo?.userId);
  467. if (!EmptyUtil.isEmpty(userInfo.userId) && !EmptyUtil.isEmpty(masterId)) {
  468. print("设置标签" + masterId + "_" + userInfo.userId);
  469. await MobPushUtil.restartPush();
  470. await MobPushUtil.setAlias(masterId + "_" + userInfo.userId);
  471. SharedPreferencesUtil.setStringValue(Constants.isSetTag, "1");
  472. }
  473. }
  474. }
  475. }
  476. final RouteObserver<Route> lifeObserver = RouteObserver();
  477. abstract class LifeState<T extends StatefulWidget> extends State<T> with RouteAware {
  478. @override
  479. void initState() {
  480. super.initState();
  481. }
  482. @override
  483. void didChangeDependencies() {
  484. lifeObserver.subscribe(this, ModalRoute.of(context));
  485. super.didChangeDependencies();
  486. }
  487. @override
  488. void dispose() {
  489. lifeObserver.unsubscribe(this);
  490. super.dispose();
  491. }
  492. void didPop() {
  493. onPaused();
  494. }
  495. void didPopNext() {
  496. onResume();
  497. print("回到首页");
  498. setState(() {});
  499. }
  500. void didPush() {
  501. onResume();
  502. }
  503. void didPushNext() {
  504. onPaused();
  505. }
  506. void onResume();
  507. void onPaused();
  508. }