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

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