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

564 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: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. WidgetsBinding.instance.removeObserver(this);
  143. streamSubscription.cancel();
  144. reloadSubscription?.cancel();
  145. logOutSubscription?.cancel();
  146. loginSubscription?.cancel();
  147. eventChannelSubscription?.cancel();
  148. super.dispose();
  149. }
  150. @override
  151. void didChangeAppLifecycleState(AppLifecycleState state) {
  152. ///智能粘贴板
  153. IntellectCreate.checkAndCreate(state, context);
  154. super.didChangeAppLifecycleState(state);
  155. }
  156. @override
  157. Widget build(BuildContext context) {
  158. ScreenUtil.init(context, width: 750, height: 1334);
  159. Logger.debug('home_page build');
  160. List<Map<String, dynamic>> tabs = _data;
  161. if (tabs == null || tabs.length == 0) {
  162. return Scaffold();
  163. }
  164. for (int i = 0; i < tabs.length;) {
  165. if (tabs[i]['is_show'] != "1") {
  166. tabs.removeAt(i);
  167. } else {
  168. i++;
  169. }
  170. }
  171. List<Widget> contentWidgets = tabs.map((item) {
  172. BaseTabModel model = BaseTabModel.fromJson(item);
  173. //首页底部创建的item,把抖券判断置true
  174. item['is_bottom_video']=true;
  175. return PageFactory.create(model.skipIdentifier, item);
  176. }).toList();
  177. if (_currentIndex >= contentWidgets.length) {
  178. _currentIndex = 0;
  179. }
  180. return Scaffold(
  181. body: IndexedStack(
  182. index: _currentIndex,
  183. children: contentWidgets,
  184. ),
  185. //底部导航栏
  186. bottomNavigationBar: createBottomNavigationBar(tabs),
  187. );
  188. }
  189. Widget createBottomNavigationBar(List<Map<String, dynamic>> tabs) {
  190. List<BottomNavigationBarItem> items = List<BottomNavigationBarItem>();
  191. for (int i = 0; i < tabs.length; i++) {
  192. BaseTabModel model = BaseTabModel.fromJson(tabs[i]);
  193. String icon = ImageUtil.getUrl(model.icon);
  194. String selectedIcon = ImageUtil.getUrl(model.chooseIcon ?? model.icon);
  195. String textColor = model.fontColor;
  196. String chooseColor = model.chooseColor ?? textColor;
  197. if (model.isShow == "1") {
  198. items.add(BottomNavigationBarItem(
  199. icon: Container(
  200. width: 24,
  201. height: 24,
  202. margin: EdgeInsets.only(bottom: 4),
  203. child: CachedNetworkImage(
  204. imageUrl: _currentIndex == i ? selectedIcon : icon,
  205. fit: BoxFit.fitWidth,
  206. ),
  207. ),
  208. title: Text(
  209. model.name,
  210. style: TextStyle(
  211. fontSize: 11,
  212. 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. /// 如果是外链,直接打开原生WebView
  239. if (model?.skipIdentifier == 'pub.flutter.url') {
  240. RouterUtil.openWebview(model?.url, context);
  241. return;
  242. }
  243. setState(() {
  244. _currentIndex = index;
  245. });
  246. EventUtil.instance.fire(model?.skipIdentifier);
  247. }
  248. }
  249. }),
  250. //底部导航栏
  251. items: items);
  252. }
  253. // Widget createBottomNavigationBarNew(List<Map<String, dynamic>> tabs) {
  254. //
  255. // List<TabItem> items = List<TabItem>();
  256. // for (int i = 0; i < tabs.length; i++) {
  257. // BaseTabModel model = BaseTabModel.fromJson(tabs[i]);
  258. // String icon = ImageUtil.getUrl(model.icon);
  259. // String selectedIcon = ImageUtil.getUrl(model.chooseIcon ?? model.icon);
  260. // String textColor = model.fontColor;
  261. // String chooseColor = model.chooseColor ?? textColor;
  262. //
  263. // if (model.isShow == "1") {
  264. // items.add(TabItem<Image>(
  265. // icon: Image.network(icon ?? ''),
  266. // activeIcon: Image.network(selectedIcon ?? ''),
  267. // title: model.name ?? ''
  268. // ));
  269. // }
  270. // }
  271. //
  272. // if (items.length < 2) {
  273. // return Container();
  274. // }
  275. // String bgColor = '#ffffff';
  276. // String textColor = '#999999';
  277. // String activeColor = '#FF4242';
  278. // if (tabs.first != null) {
  279. // BaseTabModel model = BaseTabModel.fromJson(tabs.first);
  280. // bgColor = model.bgColor ?? bgColor;
  281. // textColor = model?.fontColor ?? textColor;
  282. // activeColor = model?.chooseColor ?? activeColor;
  283. // }
  284. //
  285. // return ConvexAppBar(
  286. // elevation: 0,
  287. // backgroundColor: HexColor.fromHex(bgColor),
  288. // items: items,
  289. // height: 50,
  290. // color: HexColor.fromHex(textColor),
  291. // activeColor: HexColor.fromHex(activeColor),
  292. // initialActiveIndex: _currentIndex,
  293. // style: TabStyle.react,
  294. // onTap: (int index) async {
  295. // BaseTabModel model = BaseTabModel.fromJson(tabs[index]);
  296. // if (await _checkLimit(model)) {
  297. // ///避免同一个页面多次点击多次重绘
  298. // if (_currentIndex == index) {
  299. // return;
  300. // } else {
  301. // setState(() {
  302. // _currentIndex = index;
  303. // });
  304. // }
  305. // }
  306. // },
  307. // );
  308. // }
  309. Future<bool> _checkLimit(BaseTabModel model) async {
  310. if (model.requiredLogin == '1') {
  311. UserInfoModel user =
  312. await Provider.of<UserInfoNotifier>(context, listen: false).getUserInfoModel();
  313. print(user.toString());
  314. if (user?.token == null || user.token == '') {
  315. print('need login...');
  316. RouterUtil.goLogin(context);
  317. return false;
  318. }
  319. }
  320. return true;
  321. }
  322. ///
  323. /// 各种弹窗
  324. /// 1、用户协议弹窗 搬到启动页之前显示了
  325. /// 2、通知栏开启弹窗
  326. /// 3、活动弹窗
  327. ///
  328. Future _showPolicy() async {
  329. await Future.delayed(Duration(milliseconds: 1000), () async {
  330. // 通知弹窗
  331. ///每打开5次检查一次权限
  332. String showNotiPermissionTime = await SharedPreferencesUtil.getStringValue(
  333. Constants.showNotiPermissionTime,
  334. defaultVal: "5");
  335. int timer = int.tryParse(showNotiPermissionTime) ?? 0;
  336. if (timer % 5 == 0) {
  337. timer++;
  338. SharedPreferencesUtil.setStringValue(
  339. Constants.showNotiPermissionTime, timer.toString());
  340. if (!await Permission.storage.isGranted) {
  341. await NotificationSettingDialogNew.show(context);
  342. }
  343. String notificationAgree = await SharedPreferencesUtil.getStringValue(
  344. Constants.notificationAgree,
  345. 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(
  428. title: new Text("提示"),
  429. content: new Text(text),
  430. actions: <Widget>[
  431. new FlatButton(
  432. child: new Text("OK"),
  433. onPressed: () {
  434. Navigator.of(context).pop();
  435. },
  436. )
  437. ]));
  438. }
  439. @override
  440. void onPaused() {
  441. print("首页调用不可见");
  442. IntellectCreate.setCheck(false);
  443. }
  444. @override
  445. void onResume() {
  446. print("首页调用可见");
  447. IntellectCreate.setCheck(true);
  448. }
  449. @override
  450. // TODO: implement wantKeepAlive
  451. bool get wantKeepAlive => true;
  452. ///设置定向推送
  453. void setAlias() async {
  454. ///如果没有开启通知则设置别名
  455. if (await SharedPreferencesUtil.getStringValue(Constants.notificationAgree,
  456. defaultVal: "0") ==
  457. "1") {
  458. UserInfoModel userInfo = UserInfoNotifier?.staitcUserInfo;
  459. var setting = await NativeUtil.getSetting();
  460. String masterId = setting['master_id'];
  461. Logger.log("我的Alias: " + masterId + "_" + userInfo?.userId);
  462. if (!EmptyUtil.isEmpty(userInfo.userId) && !EmptyUtil.isEmpty(masterId)) {
  463. print("设置标签" + masterId + "_" + userInfo.userId);
  464. await MobPushUtil.restartPush();
  465. await MobPushUtil.setAlias(masterId + "_" + userInfo.userId);
  466. SharedPreferencesUtil.setStringValue(Constants.isSetTag, "1");
  467. }
  468. }
  469. }
  470. }
  471. final RouteObserver<Route> lifeObserver = RouteObserver();
  472. abstract class LifeState<T extends StatefulWidget> extends State<T> with RouteAware {
  473. @override
  474. void initState() {
  475. super.initState();
  476. }
  477. @override
  478. void didChangeDependencies() {
  479. lifeObserver.subscribe(this, ModalRoute.of(context));
  480. super.didChangeDependencies();
  481. }
  482. @override
  483. void dispose() {
  484. lifeObserver.unsubscribe(this);
  485. super.dispose();
  486. }
  487. void didPop() {
  488. onPaused();
  489. }
  490. void didPopNext() {
  491. onResume();
  492. print("回到首页");
  493. setState(() {});
  494. }
  495. void didPush() {
  496. onResume();
  497. }
  498. void didPushNext() {
  499. onPaused();
  500. }
  501. void onResume();
  502. void onPaused();
  503. }