|
- import 'dart:io';
-
- import 'package:dio/dio.dart';
- import 'package:farm_tpf/custom_model/NotificationDTO.dart';
- import 'package:farm_tpf/data/repository/repository.dart';
- import 'package:farm_tpf/data/repository/user_repository.dart';
- import 'package:farm_tpf/main.dart';
- import 'package:farm_tpf/models/index.dart';
- import 'package:farm_tpf/presentation/custom_widgets/app_bar_widget.dart';
- import 'package:farm_tpf/presentation/custom_widgets/bottom_loader.dart';
- import 'package:farm_tpf/presentation/custom_widgets/loading_list_page.dart';
- import 'package:farm_tpf/presentation/screens/plot/widget_search.dart';
- import 'package:farm_tpf/presentation/screens/plot_detail/sc_plot_detail.dart';
- import 'package:farm_tpf/presentation/screens/plot_detail/sc_plot_information.dart';
- import 'package:farm_tpf/utils/const_assets.dart';
- import 'package:farm_tpf/utils/const_color.dart';
- import 'package:farm_tpf/utils/const_common.dart';
- import 'package:farm_tpf/utils/pref.dart';
- import 'package:firebase_messaging/firebase_messaging.dart';
- import 'package:flutter/material.dart';
- import 'package:flutter_bloc/flutter_bloc.dart';
- import 'package:farm_tpf/utils/const_string.dart';
- import 'package:farm_tpf/utils/formatter.dart';
- import 'package:get/get.dart';
-
- import 'bloc/plot_bloc.dart';
-
- class PlotListScreen extends StatefulWidget {
- @override
- _PlotListScreenState createState() => _PlotListScreenState();
- }
-
- class _PlotListScreenState extends State<PlotListScreen> {
- UserRepository _userRepository = UserRepository();
- final FirebaseMessaging _firebaseMessaging = FirebaseMessaging();
- var pref = LocalPref();
- var token;
- var client;
- String pushkey = "";
- String currentFullName = "";
-
- Future<Null> getSharedPrefs() async {
- token = await pref.getString(DATA_CONST.TOKEN_KEY);
- pushkey = await pref.getString(DATA_CONST.PUSH_KEY);
- currentFullName = await pref.getString(DATA_CONST.CURRENT_FULL_NAME);
- var options = BaseOptions(baseUrl: ConstCommon.baseUrl);
- options.headers["Authorization"] = "Bearer $token";
- client = Dio(options);
- if (Platform.isIOS) {
- _firebaseMessaging
- .requestNotificationPermissions(IosNotificationSettings());
- }
- _firebaseMessaging.configure(
- onMessage: (Map<String, dynamic> message) async {
- print("onMessage: $message");
- },
- onBackgroundMessage: Platform.isIOS ? null : myBackgroundMessageHandler,
- onLaunch: (Map<String, dynamic> message) async {
- print("onLaunch: $message");
- Future.delayed(Duration(milliseconds: 500), () {
- _notificationNavigateOnFCM(message);
- });
- },
- onResume: (Map<String, dynamic> message) async {
- print("onResume: $message");
- _notificationNavigateOnFCM(message);
- },
- );
- _firebaseMessaging.requestNotificationPermissions(
- const IosNotificationSettings(
- sound: true, badge: true, alert: true, provisional: true));
- _firebaseMessaging.onIosSettingsRegistered
- .listen((IosNotificationSettings settings) {
- print("Settings registered: $settings");
- });
- if (pushkey?.isEmpty ?? true) {
- _firebaseMessaging.getToken().then((String token) {
- assert(token != null);
- print("Push Messaging token: $token");
- _userRepository.updateFcmToken(token).then((value) {
- print("send push key successful");
- pref.saveString(DATA_CONST.PUSH_KEY, token);
- });
- // client.put("");
- });
- } else {
- print("Don't need get push key");
- }
-
- if (currentFullName?.isEmpty ?? true) {
- try {
- var currentUser = await _userRepository.getUser();
- pref.saveString(DATA_CONST.CURRENT_FULL_NAME, currentUser.fullName);
- print("fullname: ${currentUser.fullName}");
- } catch (e) {
- print("error: ${e.toString()}");
- }
- }
- }
-
- _notificationNavigateOnFCM(Map<String, dynamic> message) {
- //parse data difference between Ios and Android
- var noti;
- if (Platform.isAndroid) {
- var data = message['data'];
- noti = NotificationDTO()
- ..contents = data['contents']
- ..tbCropId = data['tbCropId']
- ..type = data['type'];
- } else {
- noti = NotificationDTO.fromJson(message);
- }
- if (noti.contents == "ENV_UPDATE") {
- Get.to(PlotDetailScreen(
- cropId: noti.tbCropId,
- cropType: noti.type,
- ));
- } else if (noti.contents == "PIC_UPDATE") {
- Get.to(PlotInformationScreen(
- cropId: noti.tbCropId,
- ));
- } else {
- //Go home
- }
- }
-
- @override
- void initState() {
- super.initState();
- getSharedPrefs();
- }
-
- @override
- Widget build(BuildContext context) {
- return BlocProvider(
- create: (context) =>
- PlotBloc(repository: Repository())..add(DataFetched()),
- child: HoldInfinityWidget(),
- );
- }
- }
-
- class HoldInfinityWidget extends StatelessWidget {
- final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
- @override
- Widget build(BuildContext context) {
- return Scaffold(
- backgroundColor: Colors.white,
- key: _scaffoldKey,
- appBar: AppBarWidget(
- isBack: false,
- ),
- body: InfinityView());
- }
- }
-
- class InfinityView extends StatefulWidget {
- @override
- _InfinityViewState createState() => _InfinityViewState();
- }
-
- class _InfinityViewState extends State<InfinityView> {
- final _scrollController = ScrollController();
- final _scrollThreshold = 250.0;
- PlotBloc _plotBloc;
-
- @override
- void initState() {
- _scrollController.addListener(() {
- final maxScroll = _scrollController.position.maxScrollExtent;
- final currentScroll = _scrollController.position.pixels;
- if (maxScroll - currentScroll < _scrollThreshold) {
- _plotBloc.add(DataFetched());
- }
- });
- _plotBloc = BlocProvider.of<PlotBloc>(context);
- super.initState();
- }
-
- @override
- Widget build(BuildContext context) {
- return Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- children: <Widget>[
- Container(
- padding: EdgeInsets.all(8),
- color: Colors.white,
- child: Text(
- 'Danh sách lô trồng',
- style: TextStyle(fontWeight: FontWeight.w500, fontSize: 22),
- )),
- WidgetSearch(),
- Expanded(child: BlocBuilder<PlotBloc, PlotState>(
- builder: (context, state) {
- if (state is PlotFailure) {
- return Center(child: Text(state.errorString));
- }
- if (state is PlotSuccess) {
- if (state.items.isEmpty) {
- return Center(child: Text(label_list_empty));
- }
- return RefreshIndicator(
- child: ListView.builder(
- physics: AlwaysScrollableScrollPhysics(),
- itemBuilder: (BuildContext context, int index) {
- return index >= state.items.length
- ? BottomLoader()
- : ItemInfinityWidget(item: state.items[index]);
- },
- itemCount: state.hasReachedMax
- ? state.items.length
- : state.items.length + 1,
- controller: _scrollController,
- ),
- onRefresh: () async {
- _plotBloc.add(OnRefresh());
- });
- }
- return Center(
- child: LoadingListPage(),
- );
- },
- ))
- ],
- );
- }
-
- @override
- void dispose() {
- _scrollController.dispose();
- super.dispose();
- }
- }
-
- class ItemInfinityWidget extends StatelessWidget {
- final Crop item;
-
- const ItemInfinityWidget({Key key, @required this.item}) : super(key: key);
-
- @override
- Widget build(BuildContext context) {
- var backgroundColor;
- var textColor;
- switch (item.status) {
- case "STATUS_ARE_ACTIVE":
- backgroundColor = Colors.white;
- textColor = AppColors.DEFAULT;
- break;
- case "STATUS_FINISHED":
- backgroundColor = AppColors.DEFAULT;
- textColor = Colors.white;
- break;
- default:
- backgroundColor = Colors.white;
- textColor = Colors.black;
- }
-
- return GestureDetector(
- child: Container(
- margin: EdgeInsets.all(8),
- decoration: BoxDecoration(
- color: backgroundColor,
- border: Border.all(color: Colors.grey[300], width: 0.35),
- borderRadius: BorderRadius.circular(8),
- boxShadow: [
- BoxShadow(
- color: Colors.grey[300],
- blurRadius: 3,
- offset: Offset(0, 3))
- ]),
- padding: EdgeInsets.all(8),
- child: Row(
- children: [
- Container(
- child: Stack(
- children: [
- Image.asset(
- AppAssets.tempImage,
- width: 65,
- height: 65,
- ),
- Positioned(
- child: Container(
- color: Colors.grey.withOpacity(0.5),
- width: 65,
- height: 20,
- child: Text(
- item.areaM2.formatNumtoStringDecimal().toString() +
- " m\u00B2",
- textAlign: TextAlign.center,
- style: TextStyle(color: Colors.white)),
- ),
- bottom: 0,
- )
- ],
- ),
- ),
- SizedBox(
- width: 12,
- ),
- Expanded(
- child: Container(
- height: 75,
- child: Column(
- crossAxisAlignment: CrossAxisAlignment.start,
- mainAxisSize: MainAxisSize.min,
- children: [
- Text("${item.code ?? ''} - ${item.suppliesName ?? ''}",
- style: TextStyle(
- color: textColor, fontWeight: FontWeight.bold)),
- Expanded(
- child: SizedBox(),
- ),
- Row(
- children: [
- Icon(
- Icons.access_time,
- size: 16,
- color: textColor,
- ),
- SizedBox(
- width: 4,
- ),
- Expanded(
- child: Text(
- item.startDate.format_DDMMYY_HHmm().toString(),
- style: TextStyle(color: textColor)),
- ),
- ],
- )
- ],
- ),
- ),
- )
- ],
- ),
- ),
- onTap: () {
- Navigator.push(
- context,
- MaterialPageRoute(
- builder: (BuildContext context) => PlotDetailScreen(
- cropId: item.id,
- initialIndex: 0,
- cropType: item.type,
- )));
- });
- }
- }
|