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.

313 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 = NotificationsBloc.instance.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(const 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(const 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 ?? 0) > 99 ? '99+' : '${noti.numberUnreadTotal}';
  169. return Text(
  170. '$unreadNoti',
  171. softWrap: true,
  172. style: const TextStyle(color: Colors.white, fontSize: 10),
  173. );
  174. } else {
  175. return const 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. return SizedBox();
  202. break;
  203. case TabBarIndex.notification:
  204. return NotificationScreen();
  205. break;
  206. case TabBarIndex.account:
  207. return AccountScreen();
  208. break;
  209. default:
  210. return PlotListScreen();
  211. }
  212. }),
  213. bottomNavigationBar: Container(
  214. padding: const EdgeInsets.all(4),
  215. height: 70,
  216. decoration: const BoxDecoration(color: Colors.white, border: Border(top: BorderSide(color: Colors.grey, width: 0.35))),
  217. child: GetBuilder<TabbarSelected>(builder: (tabbarSelected) {
  218. return Center(
  219. child: ListView.builder(
  220. scrollDirection: Axis.horizontal,
  221. shrinkWrap: true,
  222. physics: const NeverScrollableScrollPhysics(),
  223. itemCount: itemsTabbar.length,
  224. itemBuilder: (context, index) {
  225. return GestureDetector(
  226. child: Container(
  227. width: (Get.width - 20) / 5,
  228. margin: const EdgeInsets.all(1),
  229. padding: const EdgeInsets.all(10),
  230. child: Column(
  231. mainAxisAlignment: MainAxisAlignment.center,
  232. children: [
  233. index == 3
  234. ? Badge(
  235. badgeContent: textCountNoti(),
  236. shape: BadgeShape.circle,
  237. badgeColor: Colors.red,
  238. position: const BadgePosition(top: -15, start: 10),
  239. child: SvgPicture.asset(
  240. itemsTabbar[index].icon,
  241. width: 24,
  242. height: 24,
  243. color: (tabbarSelected.index == itemsTabbar[index].index) ? AppColors.YELLOW : AppColors.GRAY1,
  244. ),
  245. )
  246. : SvgPicture.asset(
  247. itemsTabbar[index].icon,
  248. width: 24,
  249. height: 24,
  250. color: (tabbarSelected.index == itemsTabbar[index].index) ? AppColors.YELLOW : AppColors.GRAY1,
  251. ),
  252. Flexible(
  253. child: Text(
  254. itemsTabbar[index].title,
  255. style: TextStyle(
  256. color: (tabbarSelected.index == itemsTabbar[index].index) ? AppColors.DEFAULT : Colors.grey,
  257. fontSize: 9),
  258. ),
  259. )
  260. ],
  261. )),
  262. onTap: () {
  263. //Open scan qr code when tap icon in tabbar
  264. if (index == 2) {
  265. changeTabbar.changeIndex(changeTabbar.index);
  266. scan(context);
  267. } else {
  268. changeTabbar.changeIndex(itemsTabbar[index].index);
  269. }
  270. },
  271. );
  272. }),
  273. );
  274. })),
  275. )));
  276. }
  277. }
  278. class TabbarSelected extends GetxController {
  279. TabBarIndex index = TabBarIndex.plot;
  280. void initValue() {
  281. index = TabBarIndex.plot;
  282. update();
  283. }
  284. void changeIndex(TabBarIndex changedIndex) {
  285. index = changedIndex;
  286. update();
  287. }
  288. }
  289. enum TabBarIndex { plot, device, qr, notification, account }
  290. class TabbarItem {
  291. TabBarIndex index;
  292. String icon;
  293. String title;
  294. TabbarItem({required this.icon, required this.title, required this.index});
  295. }