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

512 lines
16 KiB

  1. import 'dart:async';
  2. import 'dart:convert' as convert;
  3. import 'package:cached_network_image/cached_network_image.dart';
  4. import 'package:flutter/cupertino.dart';
  5. import 'package:flutter/foundation.dart';
  6. import 'package:flutter/material.dart';
  7. import 'package:flutter/services.dart';
  8. import 'package:flutter/widgets.dart';
  9. import 'package:moblink/moblink.dart';
  10. import 'package:permission_handler/permission_handler.dart';
  11. import 'package:provider/provider.dart';
  12. import 'package:zhiying_base_widget/dialog/global_dialog/advertising_dialog/advertising_dialog.dart';
  13. import 'package:zhiying_base_widget/dialog/global_dialog/intellect_search_goods_dialog/intellect_create.dart';
  14. import 'package:zhiying_base_widget/dialog/global_dialog/notification_setting_dialog/notification_setting_dialog.dart';
  15. import 'package:zhiying_base_widget/dialog/tip_dialog/tip_dialog.dart';
  16. import 'package:zhiying_base_widget/models/app_config_model.dart';
  17. import 'package:zhiying_base_widget/pages/custom_page/event/reload_event.dart';
  18. import 'package:zhiying_base_widget/utils/contants.dart';
  19. import 'package:zhiying_base_widget/utils/mob_push_util.dart';
  20. import 'package:zhiying_base_widget/widgets/restart_widget/restart_widget.dart';
  21. import 'package:zhiying_comm/models/base/base_tab_model.dart';
  22. import 'package:zhiying_comm/util/image_util.dart';
  23. import 'package:zhiying_comm/util/mob_util/mob_util.dart';
  24. import 'package:sharesdk_plugin/sharesdk_plugin.dart';
  25. import 'package:zhiying_comm/util/shared_prefe_util.dart';
  26. import 'package:zhiying_comm/util/update/app_update_util.dart';
  27. import 'package:zhiying_comm/zhiying_comm.dart';
  28. import 'package:zhiying_comm/util/event_util/login_success_event.dart';
  29. import 'package:zhiying_comm/util/event_util/event_util.dart';
  30. import 'package:zhiying_comm/util/event_util/log_out.dart';
  31. import 'package:flutter_alibc/flutter_alibc.dart';
  32. import '../../models/app_config_model.dart';
  33. class HomeCenterPage extends StatefulWidget {
  34. @override
  35. _HomeCenterPageState createState() => _HomeCenterPageState();
  36. }
  37. class _HomeCenterPageState extends State<HomeCenterPage> {
  38. @override
  39. Widget build(BuildContext context) {
  40. return RestartWidget(child: HomePage());
  41. }
  42. }
  43. class HomePage extends StatefulWidget {
  44. HomePage({Key key}) : super(key: key);
  45. @override
  46. _HomePageState createState() => _HomePageState();
  47. }
  48. class _HomePageState extends LifeState<HomePage> with WidgetsBindingObserver, TickerProviderStateMixin, AutomaticKeepAliveClientMixin {
  49. int _currentIndex = 0;
  50. List<Map<String, dynamic>> _data = List();
  51. static const EventChannel _eventChannel = const EventChannel('JAVA_TO_FLUTTER');
  52. StreamSubscription streamSubscription;
  53. StreamSubscription reloadSubscription;
  54. StreamSubscription aliasSubscription;
  55. StreamSubscription logOutSubscription;
  56. StreamSubscription loginSubscription;
  57. StreamSubscription eventChannelSubscription;
  58. @override
  59. void initState() {
  60. ///初始化一些数据
  61. initAsync();
  62. //如果登出则重新打开首页
  63. streamSubscription = EventUtil.instance.on<LogOut>().listen((event) async {
  64. UserInfoModel user = await Provider.of<UserInfoNotifier>(context, listen: false).getUserInfoModel();
  65. user.token = '';
  66. Navigator.maybePop(context);
  67. print("重启1");
  68. Navigator.pushReplacementNamed(context, "/homePage");
  69. });
  70. reloadSubscription = EventUtil.instance.on<ReloadEvent>().listen((event) async {
  71. print("重启2");
  72. await BaseSettingModel.init(isGetCache: false);
  73. RestartWidget.restartApp(context);
  74. });
  75. super.initState();
  76. }
  77. ///初始化各种监听
  78. initAsync() async {
  79. try {
  80. WidgetsBinding.instance.addObserver(this);
  81. ///渲染完第一帧后调用
  82. WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
  83. int delay = ((num.tryParse(AppConfigModel.appStartDelay) ?? 0.5) * 1000).toInt();
  84. print("延时" + AppConfigModel.appStartDelay.toString());
  85. Timer(Duration(milliseconds: delay), () {
  86. NativeUtil.notifyInitSuccess();
  87. });
  88. });
  89. initBaseSet();
  90. Constants.isShowIntellectDialog = false;
  91. TaobaoAuth.initAuth(context);
  92. //弹窗
  93. _showPolicy();
  94. Moblink.uploadPrivacyPermissionStatus(1, (bool success) {});
  95. SharesdkPlugin.uploadPrivacyPermissionStatus(1, (bool success) {});
  96. // 是安卓系统,Android场景还原的实现
  97. /*if (defaultTargetPlatform == TargetPlatform.android) {
  98. }*/
  99. //app后台杀死时候的还原
  100. Moblink.restoreScene(_restore);
  101. // 监听开始(传递监听到原生端,用户监听场景还原的数据回传回来)
  102. eventChannelSubscription = _eventChannel.receiveBroadcastStream().listen(_onEvent, onError: _onError);
  103. MobPushUtil.addPushReceiver();
  104. aliasSubscription = EventUtil.instance.on<LoginSuccessEvent>().listen((event) async {
  105. UserInfoModel userInfo = UserInfoNotifier?.staitcUserInfo;
  106. var setting = await NativeUtil.getSetting();
  107. String masterId = setting['master_id'];
  108. Logger.log("我的Alias: " + masterId + "_" + userInfo?.userId);
  109. if (!EmptyUtil.isEmpty(userInfo.userId) && !EmptyUtil.isEmpty(masterId)) {
  110. MobPushUtil.setAlias(masterId + "_" + userInfo.userId);
  111. }
  112. });
  113. logOutSubscription = EventUtil.instance.on<LogOut>().listen((event) {
  114. MobPushUtil.deleteAlias();
  115. });
  116. MobPushUtil.addPushReceiver();
  117. loginSubscription = EventUtil.instance.on<LoginSuccessEvent>().listen((event) async {
  118. UserInfoModel userInfo = UserInfoNotifier?.staitcUserInfo;
  119. var setting = await NativeUtil.getSetting();
  120. String masterId = setting['master_id'];
  121. Logger.log("我的Alias: " + masterId + "_" + userInfo?.userId);
  122. if (!EmptyUtil.isEmpty(userInfo.userId) && !EmptyUtil.isEmpty(masterId)) {
  123. MobPushUtil.setAlias(masterId + "_" + userInfo.userId);
  124. }
  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. WidgetsBinding.instance.removeObserver(this);
  146. streamSubscription.cancel();
  147. reloadSubscription?.cancel();
  148. aliasSubscription?.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. return PageFactory.create(model.skipIdentifier, item);
  178. }).toList();
  179. if (_currentIndex >= contentWidgets.length) {
  180. _currentIndex = 0;
  181. }
  182. return Scaffold(
  183. body: IndexedStack(
  184. index: _currentIndex,
  185. children: contentWidgets,
  186. ),
  187. //底部导航栏
  188. bottomNavigationBar: createBottomNavigationBar(tabs),
  189. );
  190. }
  191. Widget createBottomNavigationBar(List<Map<String, dynamic>> tabs) {
  192. List<BottomNavigationBarItem> items = List<BottomNavigationBarItem>();
  193. for (int i = 0; i < tabs.length; i++) {
  194. BaseTabModel model = BaseTabModel.fromJson(tabs[i]);
  195. String icon = ImageUtil.getUrl(model.icon);
  196. String selectedIcon = ImageUtil.getUrl(model.chooseIcon ?? model.icon);
  197. String textColor = model.fontColor;
  198. String chooseColor = model.chooseColor ?? textColor;
  199. if (model.isShow == "1") {
  200. items.add(BottomNavigationBarItem(
  201. icon: Container(
  202. width: 24,
  203. height: 24,
  204. margin: EdgeInsets.only(bottom: 4),
  205. child: CachedNetworkImage(
  206. imageUrl: _currentIndex == i ? selectedIcon : icon,
  207. fit: BoxFit.fitWidth,
  208. ),
  209. ),
  210. title: Text(
  211. model.name,
  212. style: TextStyle(fontSize: 11, 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. setState(() {
  239. _currentIndex = index;
  240. });
  241. }
  242. }
  243. }),
  244. //底部导航栏
  245. items: items);
  246. }
  247. // Widget createBottomNavigationBarNew(List<Map<String, dynamic>> tabs) {
  248. //
  249. // List<TabItem> items = List<TabItem>();
  250. // for (int i = 0; i < tabs.length; i++) {
  251. // BaseTabModel model = BaseTabModel.fromJson(tabs[i]);
  252. // String icon = ImageUtil.getUrl(model.icon);
  253. // String selectedIcon = ImageUtil.getUrl(model.chooseIcon ?? model.icon);
  254. // String textColor = model.fontColor;
  255. // String chooseColor = model.chooseColor ?? textColor;
  256. //
  257. // if (model.isShow == "1") {
  258. // items.add(TabItem<Image>(
  259. // icon: Image.network(icon ?? ''),
  260. // activeIcon: Image.network(selectedIcon ?? ''),
  261. // title: model.name ?? ''
  262. // ));
  263. // }
  264. // }
  265. //
  266. // if (items.length < 2) {
  267. // return Container();
  268. // }
  269. // String bgColor = '#ffffff';
  270. // String textColor = '#999999';
  271. // String activeColor = '#FF4242';
  272. // if (tabs.first != null) {
  273. // BaseTabModel model = BaseTabModel.fromJson(tabs.first);
  274. // bgColor = model.bgColor ?? bgColor;
  275. // textColor = model?.fontColor ?? textColor;
  276. // activeColor = model?.chooseColor ?? activeColor;
  277. // }
  278. //
  279. // return ConvexAppBar(
  280. // elevation: 0,
  281. // backgroundColor: HexColor.fromHex(bgColor),
  282. // items: items,
  283. // height: 50,
  284. // color: HexColor.fromHex(textColor),
  285. // activeColor: HexColor.fromHex(activeColor),
  286. // initialActiveIndex: _currentIndex,
  287. // style: TabStyle.react,
  288. // onTap: (int index) async {
  289. // BaseTabModel model = BaseTabModel.fromJson(tabs[index]);
  290. // if (await _checkLimit(model)) {
  291. // ///避免同一个页面多次点击多次重绘
  292. // if (_currentIndex == index) {
  293. // return;
  294. // } else {
  295. // setState(() {
  296. // _currentIndex = index;
  297. // });
  298. // }
  299. // }
  300. // },
  301. // );
  302. // }
  303. Future<bool> _checkLimit(BaseTabModel model) async {
  304. if (model.requiredLogin == '1') {
  305. UserInfoModel user = await Provider.of<UserInfoNotifier>(context, listen: false).getUserInfoModel();
  306. print(user.toString());
  307. if (user?.token == null || user.token == '') {
  308. print('need login...');
  309. RouterUtil.goLogin(context);
  310. return false;
  311. }
  312. }
  313. return true;
  314. }
  315. ///
  316. /// 各种弹窗
  317. /// 1、用户协议弹窗 搬到启动页之前显示了
  318. /// 2、通知栏开启弹窗
  319. /// 3、活动弹窗
  320. ///
  321. Future _showPolicy() async {
  322. // 通知弹窗
  323. if (!await Permission.notification.isGranted) {
  324. await NotificationSettingDialog.show(context);
  325. }
  326. // 活动弹窗
  327. await AdvertisingDialog.show(context);
  328. if (!await Permission.storage.isGranted) {
  329. var result = await showDialog(
  330. context: context,
  331. child: TipDialog(
  332. content: "为了节省网络流量,我们需要获取本地存储权限,缓存信息数据。",
  333. ));
  334. if (result != null && result) {
  335. await Permission.storage.request();
  336. // 初始化百川sdk
  337. FlutterAlibc.initAlibc(version: "", appName: "").then((result) async {
  338. Logger.debug('初始化百川sdk ${result.errorCode} ${result.errorMessage}');
  339. });
  340. }
  341. }
  342. await Future.delayed(Duration(milliseconds: 600), () async {
  343. //debug app不更新 app更新插件
  344. await AppUpdateUtil.initXUpdate();
  345. // 检查app更新
  346. await AppUpdateUtil.updateApp(context);
  347. });
  348. IntellectCreate.checkAndCreateFirst(context);
  349. }
  350. // 场景还原,记录邀请码
  351. void _restore(MLSDKScene scene) {
  352. // const bool inProduction = const bool.fromEnvironment("dart.vm.product");
  353. // if (!inProduction) {
  354. // // 非release环境,弹窗测试
  355. // showAlert('要还原的路径为:' + scene.className + '\n' + scene.params.toString(),
  356. // context);
  357. // }
  358. Logger.debug('要还原的路径为:' + scene.className);
  359. try {
  360. Map<String, dynamic> params = Map<String, dynamic>.from(scene.params);
  361. if (params.containsKey('tgid')) {
  362. String tgid = params['tgid'].toString();
  363. // 记录邀请码到本地
  364. MobUtil.storeInvitedCode(tgid);
  365. }
  366. } catch (e) {
  367. Logger.error(e);
  368. }
  369. }
  370. //app存在后台时候的还原
  371. void _onEvent(Object event) {
  372. Logger.debug('返回的内容: $event');
  373. try {
  374. if (null != event) {
  375. Map<String, dynamic> params = Map<String, dynamic>.from(event);
  376. // const bool inProduction = const bool.fromEnvironment("dart.vm.product");
  377. // if (!inProduction) {
  378. // // 非release环境,弹窗测试
  379. // showAlert('要还原的路径为[活着]:$event', context);
  380. // }
  381. if (params['params'].containsKey('tgid')) {
  382. String tgid = params['params']['tgid'].toString();
  383. // 记录邀请码到本地
  384. MobUtil.storeInvitedCode(tgid);
  385. }
  386. }
  387. } catch (e) {
  388. Logger.error(e);
  389. }
  390. }
  391. void _onError(Object error) {
  392. Logger.error('返回的错误: $error');
  393. }
  394. void showAlert(String text, BuildContext context) {
  395. showDialog(
  396. context: context,
  397. builder: (BuildContext context) => CupertinoAlertDialog(title: new Text("提示"), content: new Text(text), actions: <Widget>[
  398. new FlatButton(
  399. child: new Text("OK"),
  400. onPressed: () {
  401. Navigator.of(context).pop();
  402. },
  403. )
  404. ]));
  405. }
  406. @override
  407. void onPaused() {
  408. print("首页调用不可见");
  409. IntellectCreate.setCheck(false);
  410. }
  411. @override
  412. void onResume() {
  413. print("首页调用可见");
  414. IntellectCreate.setCheck(true);
  415. }
  416. @override
  417. // TODO: implement wantKeepAlive
  418. bool get wantKeepAlive => true;
  419. }
  420. final RouteObserver<Route> lifeObserver = RouteObserver();
  421. abstract class LifeState<T extends StatefulWidget> extends State<T> with RouteAware {
  422. @override
  423. void initState() {
  424. super.initState();
  425. }
  426. @override
  427. void didChangeDependencies() {
  428. lifeObserver.subscribe(this, ModalRoute.of(context));
  429. super.didChangeDependencies();
  430. }
  431. @override
  432. void dispose() {
  433. lifeObserver.unsubscribe(this);
  434. super.dispose();
  435. }
  436. void didPop() {
  437. onPaused();
  438. }
  439. void didPopNext() {
  440. onResume();
  441. print("回到首页");
  442. setState(() {});
  443. }
  444. void didPush() {
  445. onResume();
  446. }
  447. void didPushNext() {
  448. onPaused();
  449. }
  450. void onResume();
  451. void onPaused();
  452. }