基础组件库
Ви не можете вибрати більше 25 тем Теми мають розпочинатися з літери або цифри, можуть містити дефіси (-) і не повинні перевищувати 35 символів.
 
 
 
 
 

559 рядки
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:mobcommonlib/mobcommonlib.dart';
  12. import 'package:permission_handler/permission_handler.dart';
  13. import 'package:provider/provider.dart';
  14. import 'package:zhiying_base_widget/dialog/global_dialog/advertising_dialog/advertising_dialog.dart';
  15. import 'package:zhiying_base_widget/dialog/global_dialog/intellect_search_goods_dialog/intellect_create.dart';
  16. import 'package:zhiying_base_widget/dialog/global_dialog/notification_setting_dialog/notification_setting_dialog.dart';
  17. import 'package:zhiying_base_widget/dialog/notification_dialog/notification_dialog.dart';
  18. import 'package:zhiying_base_widget/dialog/tip_dialog/tip_dialog.dart';
  19. import 'package:zhiying_base_widget/models/app_config_model.dart';
  20. import 'package:zhiying_base_widget/pages/custom_page/event/reload_event.dart';
  21. import 'package:zhiying_base_widget/utils/contants.dart';
  22. import 'package:zhiying_base_widget/utils/mob_push_util.dart';
  23. import 'package:zhiying_base_widget/widgets/restart_widget/restart_widget.dart';
  24. import 'package:zhiying_comm/models/base/base_tab_model.dart';
  25. import 'package:zhiying_comm/util/image_util.dart';
  26. import 'package:zhiying_comm/util/mob_util/mob_util.dart';
  27. import 'package:sharesdk_plugin/sharesdk_plugin.dart';
  28. import 'package:zhiying_comm/util/shared_prefe_util.dart';
  29. import 'package:zhiying_comm/util/update/app_update_util.dart';
  30. import 'package:zhiying_comm/zhiying_comm.dart';
  31. import 'package:zhiying_comm/util/event_util/login_success_event.dart';
  32. import 'package:zhiying_comm/util/event_util/event_util.dart';
  33. import 'package:zhiying_comm/util/event_util/log_out.dart';
  34. import 'package:flutter_alibc/flutter_alibc.dart';
  35. import '../../models/app_config_model.dart';
  36. class HomeCenterPage extends StatefulWidget {
  37. @override
  38. _HomeCenterPageState createState() => _HomeCenterPageState();
  39. }
  40. class _HomeCenterPageState extends State<HomeCenterPage> {
  41. @override
  42. Widget build(BuildContext context) {
  43. return RestartWidget(child: HomePage());
  44. }
  45. }
  46. class HomePage extends StatefulWidget {
  47. HomePage({Key key}) : super(key: key);
  48. @override
  49. _HomePageState createState() => _HomePageState();
  50. }
  51. class _HomePageState extends State<HomePage> 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 = await Provider.of<UserInfoNotifier>(context, listen: false).getUserInfoModel();
  67. user.token = '';
  68. Navigator.maybePop(context);
  69. print("重启1");
  70. Navigator.pushReplacementNamed(context, "/homePage");
  71. });
  72. reloadSubscription = EventUtil.instance.on<ReloadEvent>().listen((event) async {
  73. print("重启2");
  74. await BaseSettingModel.init(isGetCache: false);
  75. RestartWidget.restartApp(context);
  76. });
  77. super.initState();
  78. }
  79. ///初始化各种监听
  80. initAsync() async {
  81. try {
  82. WidgetsBinding.instance.addObserver(this);
  83. // mob锁粉隐私协议提交
  84. Moblink.uploadPrivacyPermissionStatus(1, (bool success) {});
  85. // mob分享SDK隐私协议提交
  86. SharesdkPlugin.uploadPrivacyPermissionStatus(1, (bool success) {});
  87. // mob短信SDK隐私协议提交
  88. Mobcommonlib.submitPolicyGrantResult(true, (dynamic ret, Map err) => {});
  89. // 监听开始(传递监听到原生端,用户监听场景还原的数据回传回来)
  90. eventChannelSubscription = _eventChannel.receiveBroadcastStream().listen(_onEvent, onError: _onError);
  91. ///渲染完第一帧后调用
  92. WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
  93. int delay = ((num.tryParse(AppConfigModel.appStartDelay) ?? 0.5) * 1000).toInt();
  94. print("延时" + AppConfigModel.appStartDelay.toString());
  95. Timer(Duration(milliseconds: delay), () {
  96. NativeUtil.notifyInitSuccess();
  97. //app后台杀死时候的还原
  98. Timer(Duration(milliseconds: 1500), () {
  99. Moblink.restoreScene(_restore);
  100. });
  101. });
  102. });
  103. initBaseSet();
  104. Constants.isShowIntellectDialog = false;
  105. TaobaoAuth.initAuth(context);
  106. //弹窗
  107. _showPolicy();
  108. ///设置推送标识
  109. setAlias();
  110. // 是安卓系统,Android场景还原的实现
  111. /*if (defaultTargetPlatform == TargetPlatform.android) {
  112. }*/
  113. logOutSubscription = EventUtil.instance.on<LogOut>().listen((event) {
  114. MobPushUtil.deleteAlias();
  115. SharedPreferencesUtil.setStringValue(Constants.isSetTag, "0");
  116. });
  117. MobPushUtil.addPushReceiver();
  118. loginSubscription = EventUtil.instance.on<LoginSuccessEvent>().listen((event) async {
  119. setAlias();
  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. print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>Homepagedispose>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
  141. WidgetsBinding.instance.removeObserver(this);
  142. streamSubscription.cancel();
  143. reloadSubscription?.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. //首页底部创建的item,把抖券判断置true
  173. item['is_bottom_video'] = true;
  174. return PageFactory.create(model.skipIdentifier, item);
  175. }).toList();
  176. if (_currentIndex >= contentWidgets.length) {
  177. _currentIndex = 0;
  178. }
  179. return WillPopScope(
  180. onWillPop: () async {
  181. print(">>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>HomepageBack>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>");
  182. EventUtil.instance.fire("HomepageSignOut");
  183. // 退出app
  184. // await SystemChannels.platform.invokeMethod('SystemNavigator.pop');
  185. return true;
  186. },
  187. child: Scaffold(
  188. body: IndexedStack(
  189. index: _currentIndex,
  190. children: contentWidgets,
  191. ),
  192. //底部导航栏
  193. bottomNavigationBar: createBottomNavigationBar(tabs),
  194. ),
  195. );
  196. }
  197. Widget createBottomNavigationBar(List<Map<String, dynamic>> tabs) {
  198. List<BottomNavigationBarItem> items = List<BottomNavigationBarItem>();
  199. for (int i = 0; i < tabs.length; i++) {
  200. BaseTabModel model = BaseTabModel.fromJson(tabs[i]);
  201. String icon = ImageUtil.getUrl(model.icon);
  202. String selectedIcon = ImageUtil.getUrl(model.chooseIcon ?? model.icon);
  203. String textColor = model.fontColor;
  204. String chooseColor = model.chooseColor ?? textColor;
  205. if (model.isShow == "1") {
  206. items.add(BottomNavigationBarItem(
  207. icon: Container(
  208. width: 24,
  209. height: 24,
  210. margin: EdgeInsets.only(bottom: 4),
  211. child: CachedNetworkImage(
  212. imageUrl: _currentIndex == i ? selectedIcon : icon,
  213. fit: BoxFit.fitWidth,
  214. ),
  215. ),
  216. title: Text(
  217. model.name,
  218. style: TextStyle(fontSize: 11, color: HexColor.fromHex(_currentIndex == i ? chooseColor : textColor)),
  219. )));
  220. }
  221. }
  222. if (items.length < 2) {
  223. return Container();
  224. }
  225. String bgColor = '#ffffff';
  226. if (tabs.first != null) {
  227. BaseTabModel model = BaseTabModel.fromJson(tabs.first);
  228. bgColor = model.bgColor ?? bgColor;
  229. }
  230. return BottomNavigationBar(
  231. backgroundColor: HexColor.fromHex(bgColor),
  232. type: BottomNavigationBarType.fixed,
  233. selectedFontSize: 11,
  234. unselectedFontSize: 11,
  235. currentIndex: _currentIndex,
  236. elevation: 0,
  237. onTap: ((index) async {
  238. BaseTabModel model = BaseTabModel.fromJson(tabs[index]);
  239. if (await _checkLimit(model)) {
  240. ///避免同一个页面多次点击多次重绘
  241. if (_currentIndex == index) {
  242. return;
  243. } else {
  244. /// 如果是外链,直接打开原生WebView
  245. if (model?.skipIdentifier == 'pub.flutter.url') {
  246. RouterUtil.openWebview(model?.url, context);
  247. return;
  248. }
  249. setState(() {
  250. _currentIndex = index;
  251. });
  252. EventUtil.instance.fire(model?.skipIdentifier);
  253. }
  254. }
  255. }),
  256. //底部导航栏
  257. items: items);
  258. }
  259. // Widget createBottomNavigationBarNew(List<Map<String, dynamic>> tabs) {
  260. //
  261. // List<TabItem> items = List<TabItem>();
  262. // for (int i = 0; i < tabs.length; i++) {
  263. // BaseTabModel model = BaseTabModel.fromJson(tabs[i]);
  264. // String icon = ImageUtil.getUrl(model.icon);
  265. // String selectedIcon = ImageUtil.getUrl(model.chooseIcon ?? model.icon);
  266. // String textColor = model.fontColor;
  267. // String chooseColor = model.chooseColor ?? textColor;
  268. //
  269. // if (model.isShow == "1") {
  270. // items.add(TabItem<Image>(
  271. // icon: Image.network(icon ?? ''),
  272. // activeIcon: Image.network(selectedIcon ?? ''),
  273. // title: model.name ?? ''
  274. // ));
  275. // }
  276. // }
  277. //
  278. // if (items.length < 2) {
  279. // return Container();
  280. // }
  281. // String bgColor = '#ffffff';
  282. // String textColor = '#999999';
  283. // String activeColor = '#FF4242';
  284. // if (tabs.first != null) {
  285. // BaseTabModel model = BaseTabModel.fromJson(tabs.first);
  286. // bgColor = model.bgColor ?? bgColor;
  287. // textColor = model?.fontColor ?? textColor;
  288. // activeColor = model?.chooseColor ?? activeColor;
  289. // }
  290. //
  291. // return ConvexAppBar(
  292. // elevation: 0,
  293. // backgroundColor: HexColor.fromHex(bgColor),
  294. // items: items,
  295. // height: 50,
  296. // color: HexColor.fromHex(textColor),
  297. // activeColor: HexColor.fromHex(activeColor),
  298. // initialActiveIndex: _currentIndex,
  299. // style: TabStyle.react,
  300. // onTap: (int index) async {
  301. // BaseTabModel model = BaseTabModel.fromJson(tabs[index]);
  302. // if (await _checkLimit(model)) {
  303. // ///避免同一个页面多次点击多次重绘
  304. // if (_currentIndex == index) {
  305. // return;
  306. // } else {
  307. // setState(() {
  308. // _currentIndex = index;
  309. // });
  310. // }
  311. // }
  312. // },
  313. // );
  314. // }
  315. Future<bool> _checkLimit(BaseTabModel model) async {
  316. if (model.requiredLogin == '1') {
  317. UserInfoModel user = 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(Constants.showNotiPermissionTime, defaultVal: "5");
  338. int timer = int.tryParse(showNotiPermissionTime) ?? 0;
  339. if (timer % 5 == 0) {
  340. timer++;
  341. SharedPreferencesUtil.setStringValue(Constants.showNotiPermissionTime, timer.toString());
  342. if (!await Permission.storage.isGranted) {
  343. await NotificationSettingDialogNew.show(context);
  344. }
  345. String notificationAgree = await SharedPreferencesUtil.getStringValue(Constants.notificationAgree, defaultVal: "0");
  346. if (notificationAgree == "1" && await Permission.notification.isGranted) {
  347. ///啥也不干
  348. } else {
  349. if (notificationAgree == "0" || !await Permission.notification.isGranted) {
  350. bool isGranted = await Permission.notification.isGranted;
  351. var result = await showDialog(
  352. context: context,
  353. child: NotificationDialog(
  354. isGranted: isGranted,
  355. ));
  356. if (result != null && result) {
  357. SharedPreferencesUtil.setStringValue(Constants.notificationAgree, "1");
  358. if (!await Permission.notification.isGranted) {
  359. if (Platform.isIOS) {
  360. openAppSettings();
  361. } else {
  362. await NativeUtil.openAppSettings();
  363. }
  364. }
  365. }
  366. }
  367. }
  368. }
  369. // 活动弹窗
  370. await AdvertisingDialog.show(context);
  371. IntellectCreate.checkAndCreateFirst(context);
  372. });
  373. await Future.delayed(Duration(seconds: 3), () async {
  374. //debug app不更新 app更新插件
  375. await AppUpdateUtil.initXUpdate();
  376. // 检查app更新
  377. await AppUpdateUtil.updateApp(context);
  378. });
  379. }
  380. // 场景还原,记录邀请码
  381. void _restore(MLSDKScene scene) {
  382. // const bool inProduction = const bool.fromEnvironment("dart.vm.product");
  383. // if (!inProduction) {
  384. // // 非release环境,弹窗测试
  385. // showAlert('要还原的路径为:' + scene.className + '\n' + scene.params.toString(),
  386. // context);
  387. // }
  388. Logger.debug('要还原的路径为:' + scene.className);
  389. try {
  390. Map<String, dynamic> params = Map<String, dynamic>.from(scene.params);
  391. if (params.containsKey('tgid')) {
  392. String tgid = params['tgid'].toString();
  393. // 记录邀请码到本地
  394. MobUtil.storeInvitedCode(tgid);
  395. }
  396. } catch (e) {
  397. Logger.error(e);
  398. }
  399. }
  400. //app存在后台时候的还原
  401. void _onEvent(Object event) {
  402. Logger.debug('返回的内容: $event');
  403. try {
  404. if (null != event) {
  405. Map<String, dynamic> params = Map<String, dynamic>.from(event);
  406. // const bool inProduction = const bool.fromEnvironment("dart.vm.product");
  407. // if (!inProduction) {
  408. // // 非release环境,弹窗测试
  409. // showAlert('要还原的路径为[活着]:$event', context);
  410. // }
  411. if (params['params'].containsKey('tgid')) {
  412. String tgid = params['params']['tgid'].toString();
  413. // 记录邀请码到本地
  414. MobUtil.storeInvitedCode(tgid);
  415. }
  416. }
  417. } catch (e) {
  418. Logger.error(e);
  419. }
  420. }
  421. void _onError(Object error) {
  422. Logger.error('返回的错误: $error');
  423. }
  424. void showAlert(String text, BuildContext context) {
  425. showDialog(
  426. context: context,
  427. builder: (BuildContext context) => CupertinoAlertDialog(title: new Text("提示"), content: new Text(text), actions: <Widget>[
  428. new FlatButton(
  429. child: new Text("OK"),
  430. onPressed: () {
  431. Navigator.of(context).pop();
  432. },
  433. )
  434. ]));
  435. }
  436. @override
  437. void onPaused() {
  438. print("首页调用不可见");
  439. IntellectCreate.setCheck(false);
  440. }
  441. @override
  442. void onResume() {
  443. print("首页调用可见");
  444. IntellectCreate.setCheck(true);
  445. }
  446. @override
  447. // TODO: implement wantKeepAlive
  448. bool get wantKeepAlive => true;
  449. ///设置定向推送
  450. void setAlias() async {
  451. ///如果没有开启通知则设置别名
  452. if (await SharedPreferencesUtil.getStringValue(Constants.notificationAgree, defaultVal: "0") == "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. }