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

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