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

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