基础组件库
Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.
 
 
 
 
 

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