基础组件库
Nevar pievienot vairāk kā 25 tēmas Tēmai ir jāsākas ar burtu vai ciparu, tā var saturēt domu zīmes ('-') un var būt līdz 35 simboliem gara.
 
 
 
 
 

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