基础组件库
 
 
 
 
 

374 lines
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. // ? Container(
  169. // height: initFinish?0:null,
  170. // width: double.infinity,
  171. // child: Image.asset(
  172. // 'assets/images/launch_image/launch_image.png',
  173. // package: 'zhiying_base_widget',
  174. // fit: BoxFit.cover,
  175. // ),
  176. // )
  177. // : Container(width: 0
  178. // ,height: 0,)
  179. // ],
  180. // );
  181. }
  182. Widget createBottomNavigationBar(List<Map<String, dynamic>> tabs) {
  183. List<BottomNavigationBarItem> items = List<BottomNavigationBarItem>();
  184. for (int i = 0; i < tabs.length; i++) {
  185. BaseTabModel model = BaseTabModel.fromJson(tabs[i]);
  186. String icon = ImageUtil.getUrl(model.icon);
  187. String selectedIcon = ImageUtil.getUrl(model.chooseIcon ?? model.icon);
  188. String textColor = model.fontColor;
  189. String chooseColor = model.chooseColor ?? textColor;
  190. if (model.isShow == "1") {
  191. items.add(BottomNavigationBarItem(
  192. icon: Container(
  193. width: 24,
  194. height: 24,
  195. margin: EdgeInsets.only(bottom: 4),
  196. child: CachedNetworkImage(
  197. imageUrl: _currentIndex == i ? selectedIcon : icon,
  198. fit: BoxFit.fitWidth,
  199. ),
  200. ),
  201. title: Text(
  202. model.name,
  203. style: TextStyle(fontSize: 11, color: HexColor.fromHex(_currentIndex == i ? chooseColor : textColor)),
  204. )));
  205. }
  206. }
  207. if (items.length < 2) {
  208. return Container();
  209. }
  210. String bgColor = '#ffffff';
  211. if (tabs.first != null) {
  212. BaseTabModel model = BaseTabModel.fromJson(tabs.first);
  213. bgColor = model.bgColor ?? bgColor;
  214. }
  215. return BottomNavigationBar(
  216. backgroundColor: HexColor.fromHex(bgColor),
  217. type: BottomNavigationBarType.fixed,
  218. selectedFontSize: 11,
  219. unselectedFontSize: 11,
  220. currentIndex: _currentIndex,
  221. elevation: 0,
  222. onTap: ((index) async {
  223. BaseTabModel model = BaseTabModel.fromJson(tabs[index]);
  224. if (await _checkLimit(model)) {
  225. ///避免同一个页面多次点击多次重绘
  226. if (_currentIndex == index) {
  227. return;
  228. } else {
  229. setState(() {
  230. _currentIndex = index;
  231. });
  232. }
  233. }
  234. }),
  235. //底部导航栏
  236. items: items);
  237. }
  238. Future<bool> _checkLimit(BaseTabModel model) async {
  239. if (model.requiredLogin == '1') {
  240. UserInfoModel user = await Provider.of<UserInfoNotifier>(context, listen: false).getUserInfoModel();
  241. print(user.toString());
  242. if (user?.token == null || user.token == '') {
  243. print('need login...');
  244. RouterUtil.goLogin(context);
  245. return false;
  246. }
  247. }
  248. return true;
  249. }
  250. ///
  251. /// 各种弹窗
  252. /// 1、用户协议弹窗
  253. /// 2、通知栏开启弹窗
  254. /// 3、活动弹窗
  255. ///
  256. Future _showPolicy() async {
  257. // 协议弹窗
  258. String isShowPolicy = await SharedPreferencesUtil.getStringValue(Constants.isShowPolicy);
  259. if (isShowPolicy == null || isShowPolicy != '1') {
  260. bool isAccept = await PolicyDialog.show(context);
  261. if (!isAccept) {
  262. exit(0);
  263. } else {
  264. await SharedPreferencesUtil.setStringValue(Constants.isShowPolicy, "1");
  265. }
  266. }
  267. // 通知弹窗
  268. String isShowNotiPermission = await SharedPreferencesUtil.getStringValue(Constants.isShowNotiPermission);
  269. if (isShowNotiPermission == null || isShowNotiPermission != '1') {
  270. await NotificationSettingDialog.show(context);
  271. await SharedPreferencesUtil.setStringValue(Constants.isShowNotiPermission, "1");
  272. }
  273. // 活动弹窗
  274. await ActivityDialog.show(context);
  275. await AppUpdateUtil.updateApp(context);
  276. IntellectCreate.checkAndCreateFirst(context);
  277. }
  278. // 场景还原,记录邀请码
  279. void _restore(MLSDKScene scene) {
  280. // const bool inProduction = const bool.fromEnvironment("dart.vm.product");
  281. // if (!inProduction) {
  282. // // 非release环境,弹窗测试
  283. // showAlert('要还原的路径为:' + scene.className + '\n' + scene.params.toString(),
  284. // context);
  285. // }
  286. Logger.debug('要还原的路径为:' + scene.className);
  287. try {
  288. Map<String, dynamic> params = Map<String, dynamic>.from(scene.params);
  289. if (params.containsKey('tgid')) {
  290. String tgid = params['tgid'].toString();
  291. // 记录邀请码到本地
  292. MobUtil.storeInvitedCode(tgid);
  293. }
  294. } catch (e) {
  295. Logger.error(e);
  296. }
  297. }
  298. //app存在后台时候的还原
  299. void _onEvent(Object event) {
  300. Logger.debug('返回的内容: $event');
  301. try {
  302. if (null != event) {
  303. Map<String, dynamic> params = Map<String, dynamic>.from(event);
  304. // const bool inProduction = const bool.fromEnvironment("dart.vm.product");
  305. // if (!inProduction) {
  306. // // 非release环境,弹窗测试
  307. // showAlert('要还原的路径为[活着]:$event', context);
  308. // }
  309. if (params['params'].containsKey('tgid')) {
  310. String tgid = params['params']['tgid'].toString();
  311. // 记录邀请码到本地
  312. MobUtil.storeInvitedCode(tgid);
  313. }
  314. }
  315. } catch (e) {
  316. Logger.error(e);
  317. }
  318. }
  319. void _onError(Object error) {
  320. Logger.error('返回的错误: $error');
  321. }
  322. void showAlert(String text, BuildContext context) {
  323. showDialog(
  324. context: context,
  325. builder: (BuildContext context) => CupertinoAlertDialog(title: new Text("提示"), content: new Text(text), actions: <Widget>[
  326. new FlatButton(
  327. child: new Text("OK"),
  328. onPressed: () {
  329. Navigator.of(context).pop();
  330. },
  331. )
  332. ]));
  333. }
  334. }