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

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