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.

338 lines
13KB

  1. import 'dart:io';
  2. import 'package:badges/badges.dart';
  3. import 'package:dio/dio.dart';
  4. import 'package:farm_tpf/custom_model/NotificationObjectDTO.dart';
  5. import 'package:farm_tpf/data/repository/user_repository.dart';
  6. import 'package:farm_tpf/presentation/screens/account/sc_account.dart';
  7. import 'package:farm_tpf/presentation/screens/control_device/sc_control_device.dart';
  8. import 'package:farm_tpf/presentation/screens/notification/sc_notification.dart';
  9. import 'package:farm_tpf/presentation/screens/notification/update_count_noti_bloc.dart';
  10. import 'package:farm_tpf/presentation/screens/plot/sc_plot.dart';
  11. import 'package:farm_tpf/presentation/screens/plot_detail/sc_plot_detail.dart';
  12. import 'package:farm_tpf/utils/NotificationsBloc.dart';
  13. import 'package:farm_tpf/utils/const_color.dart';
  14. import 'package:farm_tpf/utils/const_common.dart';
  15. import 'package:farm_tpf/utils/const_icons.dart';
  16. import 'package:farm_tpf/utils/pref.dart';
  17. import 'package:firebase_messaging/firebase_messaging.dart';
  18. import 'package:flutter/material.dart';
  19. import 'package:flutter_svg/flutter_svg.dart';
  20. import 'package:get/get.dart';
  21. import '../../../main.dart';
  22. class TabbarScreen extends StatefulWidget {
  23. static Route route() {
  24. return MaterialPageRoute<void>(builder: (_) => TabbarScreen());
  25. }
  26. @override
  27. _TabbarScreenState createState() => _TabbarScreenState();
  28. }
  29. class _TabbarScreenState extends State<TabbarScreen> {
  30. Stream<LocalNotification> _notificationsStream;
  31. UserRepository _userRepository = UserRepository();
  32. final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
  33. var pref = LocalPref();
  34. String pushkey = "";
  35. String currentFullName = "";
  36. var token;
  37. var client;
  38. final changeTabbar = Get.put(TabbarSelected());
  39. List<TabbarItem> itemsTabbar = [
  40. TabbarItem(
  41. icon: AppIcons.icPlot, title: 'Lô trồng', index: TabBarIndex.plot),
  42. TabbarItem(
  43. icon: AppIcons.icDevice, title: 'Thiết bị', index: TabBarIndex.device),
  44. TabbarItem(icon: AppIcons.icQr, title: 'Quét QR', index: TabBarIndex.qr),
  45. TabbarItem(
  46. icon: AppIcons.icNotification,
  47. title: 'Thông báo',
  48. index: TabBarIndex.notification),
  49. TabbarItem(
  50. icon: AppIcons.icPerson, title: 'Cá nhân', index: TabBarIndex.account)
  51. ];
  52. Future<Null> getSharedPrefs() async {
  53. token = await pref.getString(DATA_CONST.TOKEN_KEY);
  54. pushkey = await pref.getString(DATA_CONST.PUSH_KEY);
  55. currentFullName = await pref.getString(DATA_CONST.CURRENT_FULL_NAME);
  56. var options = BaseOptions(baseUrl: ConstCommon.baseUrl);
  57. options.headers["Authorization"] = "Bearer $token";
  58. client = Dio(options);
  59. if (Platform.isIOS) {
  60. _firebaseMessaging
  61. .requestNotificationPermissions(IosNotificationSettings());
  62. }
  63. _firebaseMessaging.configure(
  64. onMessage: (Map<String, dynamic> message) async {
  65. print("onMessage--tabbar-: $message");
  66. try {
  67. final String type = message['tbCropType'];
  68. final String contents = message['contents'];
  69. final String tbCropId = message['tbCropId'];
  70. updateCountNotiBloc.getNotifications((data) {}, (err) {});
  71. final notification = LocalNotification(type, contents, tbCropId);
  72. NotificationsBloc.instance.newNotification(notification);
  73. if (contents == "ENV_UPDATE") {
  74. if (Get.isSnackbarOpen) Get.back();
  75. Get.snackbar(null, 'Thông số môi trường được cập nhật');
  76. } else if (contents == "PIC_UPDATE") {
  77. if (Get.isSnackbarOpen) Get.back();
  78. Get.snackbar(null, 'Người phụ trách được cập nhật');
  79. } else {
  80. //Go home
  81. }
  82. } catch (e) {
  83. print('error');
  84. print(e);
  85. }
  86. },
  87. onBackgroundMessage: Platform.isIOS ? null : myBackgroundMessageHandler,
  88. onLaunch: (Map<String, dynamic> message) async {
  89. print("onLaunch: $message");
  90. Future.delayed(Duration(milliseconds: 500), () {
  91. updateCountNotiBloc.getNotifications((data) {}, (err) {});
  92. _notificationNavigateOnFCM(message);
  93. });
  94. },
  95. onResume: (Map<String, dynamic> message) async {
  96. print("onResume: $message");
  97. updateCountNotiBloc.getNotifications((data) {}, (err) {});
  98. _notificationNavigateOnFCM(message);
  99. },
  100. );
  101. _firebaseMessaging.requestNotificationPermissions(
  102. const IosNotificationSettings(
  103. sound: true, badge: true, alert: true, provisional: true));
  104. _firebaseMessaging.onIosSettingsRegistered
  105. .listen((IosNotificationSettings settings) {
  106. print("Settings registered: $settings");
  107. });
  108. if (pushkey?.isEmpty ?? true) {
  109. _firebaseMessaging.getToken().then((String token) {
  110. assert(token != null);
  111. print("Push Messaging token: $token");
  112. _userRepository.updateFcmToken(token).then((value) {
  113. print("send push key successful");
  114. pref.saveString(DATA_CONST.PUSH_KEY, token);
  115. });
  116. // client.put("");
  117. });
  118. } else {
  119. print("Don't need get push key");
  120. }
  121. if (currentFullName?.isEmpty ?? true) {
  122. try {
  123. var currentUser = await _userRepository.getUser();
  124. pref.saveString(DATA_CONST.CURRENT_FULL_NAME, currentUser.fullName);
  125. print("fullname: ${currentUser.fullName}");
  126. } catch (e) {
  127. print("error: ${e.toString()}");
  128. }
  129. }
  130. }
  131. @override
  132. void initState() {
  133. super.initState();
  134. getSharedPrefs();
  135. changeTabbar.initValue();
  136. updateCountNotiBloc.getNotifications((data) {}, (err) {});
  137. _notificationsStream = NotificationsBloc.instance.notificationsStream;
  138. _notificationsStream.listen((notification) {
  139. updateCountNotiBloc.getNotifications((data) {}, (err) {});
  140. print('Notification: $notification');
  141. });
  142. }
  143. _notificationNavigateOnFCM(Map<String, dynamic> message) {
  144. try {
  145. final String type = message['tbCropType'];
  146. final String contents = message['contents'];
  147. final String tbCropId = message['tbCropId'];
  148. if (contents == "ENV_UPDATE") {
  149. Get.to(PlotDetailScreen(
  150. cropType: int.parse(type),
  151. cropId: int.parse(tbCropId),
  152. initialIndex: 0,
  153. ));
  154. } else if (contents == "PIC_UPDATE") {
  155. Get.to(PlotDetailScreen(
  156. cropType: int.parse(type),
  157. cropId: int.parse(tbCropId),
  158. initialIndex: 1,
  159. ));
  160. } else {
  161. //Go home
  162. }
  163. } catch (e) {
  164. //Go home
  165. }
  166. Get.to(PlotDetailScreen(
  167. cropType: 0,
  168. cropId: 1,
  169. initialIndex: 0,
  170. ));
  171. }
  172. Widget textCountNoti() {
  173. return StreamBuilder(
  174. stream: updateCountNotiBloc.actions,
  175. builder: (context, AsyncSnapshot<dynamic> snapshot) {
  176. if (snapshot.hasData) {
  177. var noti = snapshot.data as NotificationObjectDTO;
  178. var unreadNoti =
  179. noti.numberUnreadTotal > 99 ? '99+' : '${noti.numberUnreadTotal}';
  180. return Text(
  181. '$unreadNoti',
  182. softWrap: true,
  183. style: TextStyle(color: Colors.white, fontSize: 10),
  184. );
  185. } else {
  186. return Text(
  187. 'O',
  188. softWrap: true,
  189. style: TextStyle(color: Colors.white, fontSize: 10),
  190. );
  191. }
  192. },
  193. );
  194. }
  195. @override
  196. Widget build(BuildContext context) {
  197. return Container(
  198. color: Colors.white,
  199. child: SafeArea(
  200. top: false,
  201. bottom: true,
  202. child: Scaffold(
  203. body: GetBuilder<TabbarSelected>(builder: (tabbarSelected) {
  204. switch (tabbarSelected.index) {
  205. case TabBarIndex.plot:
  206. return PlotListScreen();
  207. break;
  208. case TabBarIndex.device:
  209. return ControlDeviceScreen();
  210. break;
  211. case TabBarIndex.qr:
  212. break;
  213. case TabBarIndex.notification:
  214. return NotificationScreen();
  215. break;
  216. case TabBarIndex.account:
  217. return AccountScreen();
  218. break;
  219. default:
  220. return PlotListScreen();
  221. }
  222. }),
  223. bottomNavigationBar: Container(
  224. padding: EdgeInsets.all(4),
  225. height: 70,
  226. decoration: BoxDecoration(
  227. color: Colors.white,
  228. border: Border(
  229. top: BorderSide(color: Colors.grey, width: 0.35))),
  230. child: GetBuilder<TabbarSelected>(builder: (tabbarSelected) {
  231. return Center(
  232. child: ListView.builder(
  233. scrollDirection: Axis.horizontal,
  234. shrinkWrap: true,
  235. physics: NeverScrollableScrollPhysics(),
  236. itemCount: itemsTabbar.length,
  237. itemBuilder: (context, index) {
  238. return GestureDetector(
  239. child: Container(
  240. width: (Get.width - 20) / 5,
  241. margin: EdgeInsets.all(1),
  242. padding: EdgeInsets.all(10),
  243. child: Column(
  244. mainAxisAlignment: MainAxisAlignment.center,
  245. children: [
  246. index == 3
  247. ? Badge(
  248. badgeContent: textCountNoti(),
  249. shape: BadgeShape.circle,
  250. badgeColor: Colors.red,
  251. position: BadgePosition(
  252. top: -15, start: 10),
  253. child: SvgPicture.asset(
  254. itemsTabbar[index].icon,
  255. width: 24,
  256. height: 24,
  257. color: (tabbarSelected.index ==
  258. itemsTabbar[index]
  259. .index)
  260. ? AppColors.YELLOW
  261. : AppColors.GRAY1,
  262. ),
  263. )
  264. : SvgPicture.asset(
  265. itemsTabbar[index].icon,
  266. width: 24,
  267. height: 24,
  268. color: (tabbarSelected.index ==
  269. itemsTabbar[index].index)
  270. ? AppColors.YELLOW
  271. : AppColors.GRAY1,
  272. ),
  273. Flexible(
  274. child: Text(
  275. itemsTabbar[index].title,
  276. style: TextStyle(
  277. color: (tabbarSelected.index ==
  278. itemsTabbar[index].index)
  279. ? AppColors.DEFAULT
  280. : Colors.grey,
  281. fontSize: 9),
  282. ),
  283. )
  284. ],
  285. )),
  286. onTap: () {
  287. //Open scan qr code when tap icon in tabbar
  288. if (index == 2) {
  289. changeTabbar.changeIndex(changeTabbar.index);
  290. scan(context);
  291. } else {
  292. changeTabbar
  293. .changeIndex(itemsTabbar[index].index);
  294. }
  295. },
  296. );
  297. }),
  298. );
  299. })),
  300. )));
  301. }
  302. }
  303. class TabbarSelected extends GetxController {
  304. TabBarIndex index;
  305. void initValue() {
  306. index = TabBarIndex.plot;
  307. update();
  308. }
  309. void changeIndex(TabBarIndex changedIndex) {
  310. index = changedIndex;
  311. update();
  312. }
  313. }
  314. enum TabBarIndex { plot, device, qr, notification, account }
  315. class TabbarItem {
  316. TabBarIndex index;
  317. String icon;
  318. String title;
  319. TabbarItem({this.icon, this.title, this.index});
  320. }