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.

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