基础组件库
Non puoi selezionare più di 25 argomenti Gli argomenti devono iniziare con una lettera o un numero, possono includere trattini ('-') e possono essere lunghi fino a 35 caratteri.
 
 
 
 
 

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