基础组件库
您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符
 
 
 
 
 

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