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

387 lines
13 KiB

  1. import 'dart:async';
  2. import 'dart:convert' as convert;
  3. import 'dart:convert';
  4. import 'dart:io';
  5. import 'package:cached_network_image/cached_network_image.dart';
  6. import 'package:flutter/cupertino.dart';
  7. import 'package:flutter/foundation.dart';
  8. import 'package:flutter/material.dart';
  9. import 'package:flutter/services.dart';
  10. import 'package:flutter/widgets.dart';
  11. import 'package:moblink/moblink.dart';
  12. import 'package:mobpush_plugin/mobpush_custom_message.dart';
  13. import 'package:mobpush_plugin/mobpush_notify_message.dart';
  14. import 'package:mobpush_plugin/mobpush_plugin.dart';
  15. import 'package:provider/provider.dart';
  16. import 'package:zhiying_base_widget/dialog/global_dialog/activity_dialog/activity_dialog.dart';
  17. import 'package:zhiying_base_widget/dialog/global_dialog/advertising_dialog/advertising_dialog.dart';
  18. import 'package:zhiying_base_widget/dialog/global_dialog/intellect_search_goods_dialog/intellect_create.dart';
  19. import 'package:zhiying_base_widget/dialog/global_dialog/notification_setting_dialog/notification_setting_dialog.dart';
  20. import 'package:zhiying_base_widget/dialog/global_dialog/policy_dialog/policy_dialog.dart';
  21. import 'package:zhiying_base_widget/dialog/tip_dialog/tip_dialog.dart';
  22. import 'package:zhiying_base_widget/models/app_config_model.dart';
  23. import 'package:zhiying_base_widget/pages/custom_page/event/reload_event.dart';
  24. import 'package:zhiying_base_widget/utils/contants.dart';
  25. import 'package:zhiying_base_widget/utils/mob_push_util.dart';
  26. import 'package:zhiying_base_widget/widgets/restart_widget/restart_widget.dart';
  27. import 'package:zhiying_comm/models/base/base_tab_model.dart';
  28. import 'package:zhiying_comm/util/image_util.dart';
  29. import 'package:zhiying_comm/util/mob_util/mob_util.dart';
  30. import 'package:sharesdk_plugin/sharesdk_plugin.dart';
  31. import 'package:zhiying_comm/util/shared_prefe_util.dart';
  32. import 'package:zhiying_comm/util/update/app_update_util.dart';
  33. import 'package:zhiying_comm/zhiying_comm.dart';
  34. import 'package:zhiying_comm/util/event_util/login_success_event.dart';
  35. import 'package:zhiying_comm/util/event_util/event_util.dart';
  36. import 'package:zhiying_comm/util/event_util/log_out.dart';
  37. import 'package:zhiying_comm/util/event_util/login_success_event.dart';
  38. import 'package:zhiying_comm/util/event_util/event_util.dart';
  39. import 'package:zhiying_comm/util/event_util/log_out.dart';
  40. import 'package:package_info/package_info.dart';
  41. class HomeCenterPage extends StatefulWidget {
  42. @override
  43. _HomeCenterPageState createState() => _HomeCenterPageState();
  44. }
  45. class _HomeCenterPageState extends State<HomeCenterPage> {
  46. @override
  47. Widget build(BuildContext context) {
  48. return RestartWidget(child: HomePage());
  49. }
  50. }
  51. class HomePage extends StatefulWidget {
  52. HomePage({Key key}) : super(key: key);
  53. @override
  54. _HomePageState createState() => _HomePageState();
  55. }
  56. class _HomePageState extends State<HomePage> with WidgetsBindingObserver, TickerProviderStateMixin {
  57. int _currentIndex = 0;
  58. List<Map<String, dynamic>> _data = List();
  59. static const EventChannel _eventChannel = const EventChannel('JAVA_TO_FLUTTER');
  60. StreamSubscription streamSubscription;
  61. StreamSubscription reloadSubscription;
  62. StreamSubscription aliasSubscription;
  63. StreamSubscription logOutSubscription;
  64. StreamSubscription loginSubscription;
  65. StreamSubscription eventChannelSubscription;
  66. @override
  67. void initState() {
  68. ///初始化一些数据
  69. initAsync();
  70. //如果登出则重新打开首页
  71. streamSubscription = EventUtil.instance.on<LogOut>().listen((event) async {
  72. UserInfoModel user = await Provider.of<UserInfoNotifier>(context, listen: false).getUserInfoModel();
  73. user.token = '';
  74. Navigator.maybePop(context);
  75. print("重启1");
  76. Navigator.pushReplacementNamed(context, "/homePage");
  77. });
  78. reloadSubscription = EventUtil.instance.on<ReloadEvent>().listen((event) async {
  79. print("重启2");
  80. await BaseSettingModel.init(isGetCache: false);
  81. RestartWidget.restartApp(context);
  82. });
  83. super.initState();
  84. }
  85. ///初始化各种监听
  86. initAsync() async {
  87. try {
  88. WidgetsBinding.instance.addObserver(this);
  89. ///渲染完第一帧后调用
  90. WidgetsBinding.instance.addPostFrameCallback((timeStamp) {
  91. int delay = ((num.tryParse(AppConfigModel.appStartDelay) ?? 0.5) * 1000).toInt();
  92. Timer(Duration(milliseconds: delay), () {
  93. NativeUtil.notifyInitSuccess();
  94. });
  95. });
  96. initBaseSet();
  97. Constants.isShowIntellectDialog = false;
  98. TaobaoAuth.initAuth(context);
  99. //弹窗
  100. _showPolicy();
  101. Moblink.uploadPrivacyPermissionStatus(1, (bool success) {});
  102. SharesdkPlugin.uploadPrivacyPermissionStatus(1, (bool success) {});
  103. // 是安卓系统,Android场景还原的实现
  104. /*if (defaultTargetPlatform == TargetPlatform.android) {
  105. }*/
  106. //app后台杀死时候的还原
  107. Moblink.restoreScene(_restore);
  108. // 监听开始(传递监听到原生端,用户监听场景还原的数据回传回来)
  109. eventChannelSubscription= _eventChannel.receiveBroadcastStream().listen(_onEvent, onError: _onError);
  110. MobPushUtil.addPushReceiver();
  111. aliasSubscription = EventUtil.instance.on<LoginSuccessEvent>().listen((event) async {
  112. UserInfoModel userInfo = UserInfoNotifier?.staitcUserInfo;
  113. var setting = await NativeUtil.getSetting();
  114. String masterId = setting['master_id'];
  115. Logger.log("我的Alias: " + masterId + "_" + userInfo?.userId);
  116. if (!EmptyUtil.isEmpty(userInfo.userId) && !EmptyUtil.isEmpty(masterId)) {
  117. MobPushUtil.setAlias(masterId + "_" + userInfo.userId);
  118. }
  119. });
  120. logOutSubscription = EventUtil.instance.on<LogOut>().listen((event) {
  121. MobPushUtil.deleteAlias();
  122. });
  123. MobPushUtil.addPushReceiver();
  124. loginSubscription = EventUtil.instance.on<LoginSuccessEvent>().listen((event) async {
  125. UserInfoModel userInfo = UserInfoNotifier?.staitcUserInfo;
  126. var setting = await NativeUtil.getSetting();
  127. String masterId = setting['master_id'];
  128. Logger.log("我的Alias: " + masterId + "_" + userInfo?.userId);
  129. if (!EmptyUtil.isEmpty(userInfo.userId) && !EmptyUtil.isEmpty(masterId)) {
  130. MobPushUtil.setAlias(masterId + "_" + userInfo.userId);
  131. }
  132. });
  133. } catch (e, s) {
  134. print(e);
  135. print(s);
  136. }
  137. }
  138. initBaseSet() {
  139. String data = BaseSettingModel.setting.tab['data'];
  140. try {
  141. List list = convert.jsonDecode(data);
  142. _data = list.map((item) {
  143. return Map<String, dynamic>.from(item);
  144. }).toList();
  145. Logger.debug(_data);
  146. } catch (error) {
  147. Logger.error(error);
  148. }
  149. }
  150. @override
  151. void dispose() {
  152. WidgetsBinding.instance.removeObserver(this);
  153. streamSubscription.cancel();
  154. reloadSubscription?.cancel();
  155. aliasSubscription?.cancel();
  156. logOutSubscription?.cancel();
  157. loginSubscription?.cancel();
  158. eventChannelSubscription?.cancel();
  159. super.dispose();
  160. }
  161. @override
  162. void didChangeAppLifecycleState(AppLifecycleState state) {
  163. ///智能粘贴板
  164. IntellectCreate.checkAndCreate(state, context);
  165. super.didChangeAppLifecycleState(state);
  166. }
  167. @override
  168. Widget build(BuildContext context) {
  169. ScreenUtil.init(context, width: 750, height: 1334);
  170. Logger.debug('home_page build');
  171. List<Map<String, dynamic>> tabs = _data;
  172. if (tabs == null || tabs.length == 0) {
  173. return Scaffold();
  174. }
  175. for (int i = 0; i < tabs.length;) {
  176. if (tabs[i]['is_show'] != "1") {
  177. tabs.removeAt(i);
  178. } else {
  179. i++;
  180. }
  181. }
  182. List<Widget> contentWidgets = tabs.map((item) {
  183. BaseTabModel model = BaseTabModel.fromJson(item);
  184. return PageFactory.create(model.skipIdentifier, item);
  185. }).toList();
  186. if (_currentIndex >= contentWidgets.length) {
  187. _currentIndex = 0;
  188. }
  189. return Scaffold(
  190. body: IndexedStack(
  191. index: _currentIndex,
  192. children: contentWidgets,
  193. ),
  194. //底部导航栏
  195. bottomNavigationBar: createBottomNavigationBar(tabs),
  196. );
  197. }
  198. Widget createBottomNavigationBar(List<Map<String, dynamic>> tabs) {
  199. List<BottomNavigationBarItem> items = List<BottomNavigationBarItem>();
  200. for (int i = 0; i < tabs.length; i++) {
  201. BaseTabModel model = BaseTabModel.fromJson(tabs[i]);
  202. String icon = ImageUtil.getUrl(model.icon);
  203. String selectedIcon = ImageUtil.getUrl(model.chooseIcon ?? model.icon);
  204. String textColor = model.fontColor;
  205. String chooseColor = model.chooseColor ?? textColor;
  206. if (model.isShow == "1") {
  207. items.add(BottomNavigationBarItem(
  208. icon: Container(
  209. width: 24,
  210. height: 24,
  211. margin: EdgeInsets.only(bottom: 4),
  212. child: CachedNetworkImage(
  213. imageUrl: _currentIndex == i ? selectedIcon : icon,
  214. fit: BoxFit.fitWidth,
  215. ),
  216. ),
  217. title: Text(
  218. model.name,
  219. style: TextStyle(fontSize: 11, color: HexColor.fromHex(_currentIndex == i ? chooseColor : textColor)),
  220. )));
  221. }
  222. }
  223. if (items.length < 2) {
  224. return Container();
  225. }
  226. String bgColor = '#ffffff';
  227. if (tabs.first != null) {
  228. BaseTabModel model = BaseTabModel.fromJson(tabs.first);
  229. bgColor = model.bgColor ?? bgColor;
  230. }
  231. return BottomNavigationBar(
  232. backgroundColor: HexColor.fromHex(bgColor),
  233. type: BottomNavigationBarType.fixed,
  234. selectedFontSize: 11,
  235. unselectedFontSize: 11,
  236. currentIndex: _currentIndex,
  237. elevation: 0,
  238. onTap: ((index) async {
  239. BaseTabModel model = BaseTabModel.fromJson(tabs[index]);
  240. if (await _checkLimit(model)) {
  241. ///避免同一个页面多次点击多次重绘
  242. if (_currentIndex == index) {
  243. return;
  244. } else {
  245. setState(() {
  246. _currentIndex = index;
  247. });
  248. }
  249. }
  250. }),
  251. //底部导航栏
  252. items: items);
  253. }
  254. Future<bool> _checkLimit(BaseTabModel model) async {
  255. if (model.requiredLogin == '1') {
  256. UserInfoModel user = await Provider.of<UserInfoNotifier>(context, listen: false).getUserInfoModel();
  257. print(user.toString());
  258. if (user?.token == null || user.token == '') {
  259. print('need login...');
  260. RouterUtil.goLogin(context);
  261. return false;
  262. }
  263. }
  264. return true;
  265. }
  266. ///
  267. /// 各种弹窗
  268. /// 1、用户协议弹窗 搬到启动页之前显示了
  269. /// 2、通知栏开启弹窗
  270. /// 3、活动弹窗
  271. ///
  272. Future _showPolicy() async {
  273. // 通知弹窗
  274. String isShowNotiPermission = await SharedPreferencesUtil.getStringValue(Constants.isShowNotiPermission);
  275. if (isShowNotiPermission == null || isShowNotiPermission != '1') {
  276. await NotificationSettingDialog.show(context);
  277. await SharedPreferencesUtil.setStringValue(Constants.isShowNotiPermission, "1");
  278. }
  279. // 活动弹窗
  280. await AdvertisingDialog.show(context);
  281. await AppUpdateUtil.updateApp(context);
  282. IntellectCreate.checkAndCreateFirst(context);
  283. }
  284. // 场景还原,记录邀请码
  285. void _restore(MLSDKScene scene) {
  286. // const bool inProduction = const bool.fromEnvironment("dart.vm.product");
  287. // if (!inProduction) {
  288. // // 非release环境,弹窗测试
  289. // showAlert('要还原的路径为:' + scene.className + '\n' + scene.params.toString(),
  290. // context);
  291. // }
  292. Logger.debug('要还原的路径为:' + scene.className);
  293. try {
  294. Map<String, dynamic> params = Map<String, dynamic>.from(scene.params);
  295. if (params.containsKey('tgid')) {
  296. String tgid = params['tgid'].toString();
  297. // 记录邀请码到本地
  298. MobUtil.storeInvitedCode(tgid);
  299. }
  300. } catch (e) {
  301. Logger.error(e);
  302. }
  303. }
  304. //app存在后台时候的还原
  305. void _onEvent(Object event) {
  306. Logger.debug('返回的内容: $event');
  307. try {
  308. if (null != event) {
  309. Map<String, dynamic> params = Map<String, dynamic>.from(event);
  310. // const bool inProduction = const bool.fromEnvironment("dart.vm.product");
  311. // if (!inProduction) {
  312. // // 非release环境,弹窗测试
  313. // showAlert('要还原的路径为[活着]:$event', context);
  314. // }
  315. if (params['params'].containsKey('tgid')) {
  316. String tgid = params['params']['tgid'].toString();
  317. // 记录邀请码到本地
  318. MobUtil.storeInvitedCode(tgid);
  319. }
  320. }
  321. } catch (e) {
  322. Logger.error(e);
  323. }
  324. }
  325. void _onError(Object error) {
  326. Logger.error('返回的错误: $error');
  327. }
  328. void showAlert(String text, BuildContext context) {
  329. showDialog(
  330. context: context,
  331. builder: (BuildContext context) => CupertinoAlertDialog(title: new Text("提示"), content: new Text(text), actions: <Widget>[
  332. new FlatButton(
  333. child: new Text("OK"),
  334. onPressed: () {
  335. Navigator.of(context).pop();
  336. },
  337. )
  338. ]));
  339. }
  340. }