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.

312 lines
12KB

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