From 10b8680490671d844045833eadfb276f34df9add Mon Sep 17 00:00:00 2001 From: "Vicente J. Ruiz Jurado" Date: Fri, 3 Aug 2018 23:07:13 +0200 Subject: [PATCH] Fire notification dialog. Connectivity dialgo --- lib/firesApp.dart | 131 +---------------------- lib/generated/i18n.dart | 3 + lib/homePage.dart | 176 ++++++++++++++++++++++++++++++- lib/mainCommon.dart | 1 + lib/models/fireNotification.dart | 7 +- res/values/strings_en.arb | 3 +- res/values/strings_es.arb | 3 +- 7 files changed, 184 insertions(+), 140 deletions(-) diff --git a/lib/firesApp.dart b/lib/firesApp.dart index 420e3b1..14f5725 100644 --- a/lib/firesApp.dart +++ b/lib/firesApp.dart @@ -1,12 +1,6 @@ -import 'dart:async'; -import 'package:bson_objectid/bson_objectid.dart'; import 'package:comunes_flutter/comunes_flutter.dart'; -import 'package:connectivity/connectivity.dart'; -import 'package:firebase_messaging/firebase_messaging.dart'; -import 'package:fires_flutter/models/fireNotification.dart'; import 'package:flutter/material.dart'; -import 'package:flutter/services.dart'; import 'package:flutter_localizations/flutter_localizations.dart'; import 'package:flutter_redux/flutter_redux.dart'; import 'package:redux/redux.dart'; @@ -53,36 +47,11 @@ class _FiresAppState extends State { }; final Store store; - String _connectionStatus = 'Unknown'; - final Connectivity _connectivity = new Connectivity(); - StreamSubscription _connectivitySubscription; + // globals.getIt.registerSingleton _FiresAppState(this.store); - // Platform messages are asynchronous, so we initialize in an async method. - Future initConnectivity() async { - String connectionStatus; - // Platform messages may fail, so we use a try/catch PlatformException. - try { - connectionStatus = (await _connectivity.checkConnectivity()).toString(); - } on PlatformException catch (e) { - print(e.toString()); - connectionStatus = 'Failed to get connectivity.'; - } - - // If the widget was removed from the tree while the asynchronous platform - // message was in flight, we want to discard the reply rather than calling - // setState to update our non-existent appearance. - if (!mounted) { - return; - } - - setState(() { - // store.dispatch(action); - _connectionStatus = connectionStatus; - }); - } @override Widget build(BuildContext context) { @@ -112,102 +81,4 @@ class _FiresAppState extends State { theme: firesTheme, routes: routes)); } - - @override - void initState() { - super.initState(); - _firebaseMessaging.configure(onMessage: (Map message) { - debugPrint("onMessage in fireApp: $message"); - _showItemDialog(message, store); - }, onLaunch: (Map message) { - debugPrint("onLaunch: $message"); - _navigateToItemDetail(message, store); - }, onResume: (Map message) { - debugPrint("onResume: $message"); - _navigateToItemDetail(message, store); - }); - _firebaseMessaging.requestNotificationPermissions( - const IosNotificationSettings(sound: true, badge: true, alert: true)); - _firebaseMessaging.onIosSettingsRegistered - .listen((IosNotificationSettings settings) { - print("Settings registered: $settings"); - }); - _firebaseMessaging.getToken().then((String token) { - assert(token != null); - store.dispatch(new OnUserTokenAction(token)); - setState(() {}); - }); - initConnectivity(); - _connectivitySubscription = - _connectivity.onConnectivityChanged.listen((ConnectivityResult result) { - setState(() => _connectionStatus = result.toString()); - }); - } - - void _showItemDialog(Map message, Store store) { - final notif = _notifForMessage(message); - showDialog( - context: navigatorKey.currentContext, - builder: (_) => _buildDialog(navigatorKey.currentContext, notif), - ).then((bool shouldNavigate) { - if (shouldNavigate == true) { - _navigateToItemDetail(message, store); - } - }).catchError((e) => print("$e")); - } - - Widget _buildDialog(BuildContext context, FireNotification item) { - return new AlertDialog( - content: new Text(item.description), - actions: [ - new FlatButton( - child: Text(S.of(context).CLOSE), - onPressed: () { - Navigator.pop(context, false); - }, - ), - new FlatButton( - child: Text(S.of(context).SHOW), - onPressed: () { - Navigator.pop(context, true); - }, - ), - ], - ); - } - - void _navigateToItemDetail(Map message, Store store) { - FireNotification notif = _notifForMessage(message); - // Clear away dialogs - Navigator.popUntil(navigatorKey.currentContext, - (Route route) => route is PageRoute); - if (!notif.getRoute(store).isCurrent) { - Navigator.push(navigatorKey.currentContext, notif.getRoute(store)); - } - } - - // https://pub.dartlang.org/packages/firebase_messaging#-example-tab- - final FirebaseMessaging _firebaseMessaging = new FirebaseMessaging(); - - FireNotification _notifForMessage(Map message) { - FireNotification notif; - // print('start parse notif'); - try { - notif = new FireNotification( - id: new ObjectId.fromHexString(message['id']), - subsId: new ObjectId.fromHexString(message['subsId']), - lat: double.parse(message['lat']), - lon: double.parse(message['lon']), - description: message['description'], - read: false, - when: DateTime.parse(message['when']), - sealed: message['sealed']); - // print('end parse notif'); - debugPrint(notif.toString()); - } catch (e) { - debugPrint(e.toString()); - } - if (notif != null) store.dispatch(new AddFireNotificationAction(notif)); - return notif; - } } diff --git a/lib/generated/i18n.dart b/lib/generated/i18n.dart index 0267484..318df4d 100644 --- a/lib/generated/i18n.dart +++ b/lib/generated/i18n.dart @@ -57,6 +57,7 @@ class S implements WidgetsLocalizations { String get firesNearPlace => "Fires near other place"; String get getAlertsOfFiresinThatArea => "Get alerts of fires in that area"; String get isYourUbicationEnabled => "I cannot get your current location. It's your ubication enabled?"; + String get noConnectivity => "This app require an Internet connection"; String get noFiresAround => "There is no fires"; String get notPermsUbication => "We don't have permission to get your location"; String get notifyAFire => "Notify a fire"; @@ -125,6 +126,8 @@ class es extends S { @override String get tweetAboutAFireDescription => "Adicionalmente si usas twitter puedes compartir información adicional con los servicios de emergencia, por ejemplo, adjuntando fotos al tweet si tienes buena visibilidad del fuego, cuando tomaste las fotos, ubicación exacta, etc. Usa #hashtags tipo #IFTerminoMunicipal por ejemplo #IFJumilla (Incendio Forestal en Jumilla)."; @override + String get noConnectivity => "Esta aplicación necesita conexión a Internet"; + @override String get AvoidThisStringsIfisNotPlural => "Zero One Two Few Many Other"; @override String get unsubscribe => "Desuscríbete"; diff --git a/lib/homePage.dart b/lib/homePage.dart index 7cac249..3b01789 100644 --- a/lib/homePage.dart +++ b/lib/homePage.dart @@ -1,15 +1,100 @@ import 'package:comunes_flutter/comunes_flutter.dart'; import 'package:flutter/material.dart'; - +import 'package:firebase_messaging/firebase_messaging.dart'; +import 'package:fires_flutter/models/fireNotification.dart'; +import 'redux/actions.dart'; import 'activeFires.dart'; import 'fireAlert.dart'; import 'colors.dart'; import 'generated/i18n.dart'; import 'mainDrawer.dart'; - -class HomePage extends StatelessWidget { +import 'package:connectivity/connectivity.dart'; +import 'dart:async'; +import 'package:flutter/services.dart'; +import 'package:redux/redux.dart'; +import 'models/appState.dart'; +import 'package:bson_objectid/bson_objectid.dart'; +import 'package:flutter_simple_dependency_injection/injector.dart'; +import 'fireNotificationList.dart'; +class HomePage extends StatefulWidget { static const String routeName = '/home'; + + HomePage(); + + @override + _HomePageState createState() => _HomePageState(); +} + +class _HomePageState extends State { final GlobalKey _scaffoldKey = new GlobalKey(); + final Store store = Injector.getInjector().get>(); + + final Connectivity _connectivity = new Connectivity(); + + // Platform messages are asynchronous, so we initialize in an async method. + Future initConnectivity() async { + ConnectivityResult connectionStatus; + // Platform messages may fail, so we use a try/catch PlatformException. + try { + connectionStatus = (await _connectivity.checkConnectivity()); + } on PlatformException catch (e) { + print(e.toString()); + connectionStatus = ConnectivityResult.none; + } + + // If the widget was removed from the tree while the asynchronous platform + // message was in flight, we want to discard the reply rather than calling + // setState to update our non-existent appearance. + if (!mounted) { + return; + } + + setState(() { + store.dispatch(new OnConnectivityChanged(connectionStatus)); + if (connectionStatus == ConnectivityResult.none) { + _showDialog(S + .of(context) + .noConnectivity); + } + }); + } + + @override + void initState() { + super.initState(); + _firebaseMessaging.configure(onMessage: (Map message) { + debugPrint("onMessage in fireApp: $message"); + _showItemDialog(message); + }, onLaunch: (Map message) { + debugPrint("onLaunch: $message"); + _navigateToItemDetail(message); + }, onResume: (Map message) { + debugPrint("onResume: $message"); + _navigateToItemDetail(message); + }); + _firebaseMessaging.requestNotificationPermissions( + const IosNotificationSettings(sound: true, badge: true, alert: true)); + _firebaseMessaging.onIosSettingsRegistered + .listen((IosNotificationSettings settings) { + print("Settings registered: $settings"); + }); + _firebaseMessaging.getToken().then((String token) { + assert(token != null); + store.dispatch(new OnUserTokenAction(token)); + setState(() {}); + }); + initConnectivity(); + // StreamSubscription _connectivitySubscription = + _connectivity.onConnectivityChanged.listen((ConnectivityResult result) { + if (!mounted) { + return; + } + setState(() { + store.dispatch(new OnConnectivityChanged(result)); + // _showDialog(result.toString()); + }); + }); + } final _homeFont = const TextStyle( fontSize: 50.0, @@ -96,4 +181,89 @@ class HomePage extends StatelessWidget { ])), )); } + + + + void _showDialog(String message) { + showDialog( + context: _scaffoldKey.currentContext, + builder: (_) => new AlertDialog( + content: new Text(message), + actions: [ + new FlatButton( + child: Text(S.of(_scaffoldKey.currentContext).CLOSE), + onPressed: () { + Navigator.pop(_scaffoldKey.currentContext); + }, + ), + ], + )); + } + + void _showItemDialog(Map message) { + final notif = _notifForMessage(message); + showDialog( + context: _scaffoldKey.currentContext, + builder: (_) => _buildDialog(_scaffoldKey.currentContext, notif), + ).then((bool shouldNavigate) { + if (shouldNavigate == true) { + _navigateToItemDetail(message); + } + }).catchError((e) => print("$e")); + } + + Widget _buildDialog(BuildContext context, FireNotification item) { + return new AlertDialog( + content: new Text(item.description), + actions: [ + new FlatButton( + child: Text(S.of(context).CLOSE), + onPressed: () { + Navigator.pop(context, false); + }, + ), + new FlatButton( + child: Text(S.of(context).SHOW), + onPressed: () { + Navigator.pop(context, true); + }, + ), + ], + ); + } + + void _navigateToItemDetail(Map message) { + _notifForMessage(message); + // Clear away dialogs + Navigator.popUntil(_scaffoldKey.currentContext, + (Route route) => route is PageRoute); + /* if (!notif.getRoute(store).isCurrent) { + // Navigator.push(_scaffoldKey.currentContext, notif.getRoute(store)); + } */ + Navigator.pushNamed(_scaffoldKey.currentContext, FireNotificationList.routeName); + } + + // https://pub.dartlang.org/packages/firebase_messaging#-example-tab- + final FirebaseMessaging _firebaseMessaging = new FirebaseMessaging(); + + FireNotification _notifForMessage(Map message) { + FireNotification notif; + try { + notif = new FireNotification( + id: new ObjectId.fromHexString(message['id']), + subsId: new ObjectId.fromHexString(message['subsId']), + lat: double.parse(message['lat']), + lon: double.parse(message['lon']), + description: message['description'], + read: false, + when: DateTime.parse(message['when']), + sealed: message['sealed']); + debugPrint(notif.toString()); + } catch (e) { + debugPrint(e.toString()); + } + if (notif != null) store.dispatch(new AddFireNotificationAction(notif)); + return notif; + } + } diff --git a/lib/mainCommon.dart b/lib/mainCommon.dart index 7566322..2fca808 100644 --- a/lib/mainCommon.dart +++ b/lib/mainCommon.dart @@ -31,6 +31,7 @@ void mainCommon(List> otherMiddleware) { middleware: List.from(otherMiddleware) ..add(fetchDataMiddleware)); + injector.map>((i) => store); injector.map((i) => store.state.firesApiUrl, key: "firesApiUrl"); injector.map((i) => store.state.firesApiKey, key: "firesApiKey"); injector.map((i) => store.state.serverUrl, key: "serverUrl"); diff --git a/lib/models/fireNotification.dart b/lib/models/fireNotification.dart index 0ebbf2f..5c3cef4 100644 --- a/lib/models/fireNotification.dart +++ b/lib/models/fireNotification.dart @@ -2,11 +2,7 @@ import 'package:bson_objectid/bson_objectid.dart'; import 'package:comunes_flutter/comunes_flutter.dart'; import 'package:flutter/material.dart'; import 'package:json_annotation/json_annotation.dart'; -import 'package:redux/src/store.dart'; - -import '../genericMap.dart'; import '../objectIdUtils.dart'; -import '../redux/actions.dart'; part 'fireNotification.g.dart'; @@ -84,6 +80,7 @@ class FireNotification extends Object with _$FireNotificationSerializerMixin { static final Map> routes = >{}; + /* Route getRoute(Store store) { final String routeName = '/fire/${id}'; return routes.putIfAbsent( @@ -99,5 +96,5 @@ class FireNotification extends Object with _$FireNotificationSerializerMixin { }, ), ); - } + } */ } diff --git a/res/values/strings_en.arb b/res/values/strings_en.arb index 428dca0..f8a9139 100644 --- a/res/values/strings_en.arb +++ b/res/values/strings_en.arb @@ -63,5 +63,6 @@ "deleteAllFireNotificationsAlertDescription": "This will remove all your fire notifications", "DELETE": "DELETE", "SHOW": "SHOW", - "CLOSE": "CLOSE" + "CLOSE": "CLOSE", + "noConnectivity": "This app require an Internet connection" } \ No newline at end of file diff --git a/res/values/strings_es.arb b/res/values/strings_es.arb index a83745d..a8372eb 100644 --- a/res/values/strings_es.arb +++ b/res/values/strings_es.arb @@ -63,5 +63,6 @@ "deleteAllFireNotificationsAlertDescription": "Esto borrará todas las notificaciones de fuegos", "DELETE": "BORRAR", "SHOW": "MOSTRAR", - "CLOSE": "CERRAR" + "CLOSE": "CERRAR", + "noConnectivity": "Esta aplicación necesita conexión a Internet" } \ No newline at end of file