基础组件库
選択できるのは25トピックまでです。 トピックは、先頭が英数字で、英数字とダッシュ('-')を使用した35文字以内のものにしてください。
 
 
 
 
 

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