More redux work

This commit is contained in:
vjrj 2018-06-27 22:29:54 +02:00
parent 69428c5d96
commit 5d947f9577
14 changed files with 170 additions and 88 deletions

View file

@ -1,19 +1,50 @@
import 'dart:async'; import 'dart:async';
import 'package:comunes_flutter/comunes_flutter.dart'; import 'package:comunes_flutter/comunes_flutter.dart';
import 'package:fires_flutter/models/yourLocation.dart';
import 'package:flutter/material.dart'; import 'package:flutter/material.dart';
import 'package:flutter_fab_dialer/flutter_fab_dialer.dart'; import 'package:flutter_fab_dialer/flutter_fab_dialer.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'colors.dart'; import 'colors.dart';
import 'generated/i18n.dart'; import 'generated/i18n.dart';
import 'genericMap.dart'; import 'genericMap.dart';
import 'globalFiresBottomStats.dart'; import 'globalFiresBottomStats.dart';
import 'globals.dart' as globals;
import 'locationUtils.dart'; import 'locationUtils.dart';
import 'mainDrawer.dart'; import 'mainDrawer.dart';
import 'models/appState.dart';
import 'placesAutocompleteUtils.dart'; import 'placesAutocompleteUtils.dart';
import 'package:fires_flutter/models/yourLocation.dart'; import 'redux/actions.dart';
import 'package:fires_flutter/models/yourLocationPersist.dart';
class _ViewModel {
final List<YourLocation> yourLocations;
final AddYourLocationFunction onAdd;
final DeleteYourLocationFunction onDelete;
final ToggleSubscriptionFunction onToggleSubs;
_ViewModel(
{@required this.onAdd,
@required this.onDelete,
@required this.onToggleSubs,
@required this.yourLocations});
@override
bool operator ==(Object other) =>
identical(this, other) ||
other is _ViewModel &&
runtimeType == other.runtimeType &&
yourLocations == other.yourLocations &&
onAdd == other.onAdd &&
onDelete == other.onDelete &&
onToggleSubs == other.onToggleSubs;
@override
int get hashCode =>
yourLocations.hashCode ^
onAdd.hashCode ^
onDelete.hashCode ^
onToggleSubs.hashCode;
}
class ActiveFiresPage extends StatefulWidget { class ActiveFiresPage extends StatefulWidget {
static const String routeName = '/fires'; static const String routeName = '/fires';
@ -27,7 +58,7 @@ class ActiveFiresPage extends StatefulWidget {
class _ActiveFiresPageState extends State<ActiveFiresPage> { class _ActiveFiresPageState extends State<ActiveFiresPage> {
final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>(); final GlobalKey<ScaffoldState> _scaffoldKey = new GlobalKey<ScaffoldState>();
List<FabMiniMenuItem> _fabMiniMenuItemList() { List<FabMiniMenuItem> _fabMiniMenuItemList(AddYourLocationFunction onAdd) {
return [ return [
new FabMiniMenuItem.withText( new FabMiniMenuItem.withText(
new Icon(Icons.location_searching), new Icon(Icons.location_searching),
@ -35,7 +66,7 @@ class _ActiveFiresPageState extends State<ActiveFiresPage> {
8.0, 8.0,
S.of(context).addYourCurrentPosition, S.of(context).addYourCurrentPosition,
() { () {
onAddYourLocation(); onAddYourLocation(onAdd);
}, },
S.of(context).addYourCurrentPosition, S.of(context).addYourCurrentPosition,
Colors.black38, Colors.black38,
@ -43,14 +74,14 @@ class _ActiveFiresPageState extends State<ActiveFiresPage> {
), ),
new FabMiniMenuItem.withText(new Icon(Icons.edit_location), fires600, 8.0, new FabMiniMenuItem.withText(new Icon(Icons.edit_location), fires600, 8.0,
S.of(context).addSomePlace, () { S.of(context).addSomePlace, () {
onAddOtherLocation(); onAddOtherLocation(onAdd);
}, S.of(context).addSomePlace, Colors.black38, Colors.white) }, S.of(context).addSomePlace, Colors.black38, Colors.white)
]; ];
} }
_ActiveFiresPageState(); _ActiveFiresPageState();
Widget _buildRow(YourLocation loc) { Widget _buildRow(YourLocation loc, onToggle) {
return new ListTile( return new ListTile(
dense: true, dense: true,
leading: const Icon(Icons.location_on), leading: const Icon(Icons.location_on),
@ -60,10 +91,11 @@ class _ActiveFiresPageState extends State<ActiveFiresPage> {
: Icons.notifications_off), : Icons.notifications_off),
onPressed: () { onPressed: () {
loc.subscribed = !loc.subscribed; loc.subscribed = !loc.subscribed;
int i = globals.yourLocations.indexOf(loc); onToggle(loc.id);
/* FIXME int i = globals.yourLocations.indexOf(loc);
globals.yourLocations.removeAt(i); globals.yourLocations.removeAt(i);
globals.yourLocations.insert(i, loc); globals.yourLocations.insert(i, loc);
persistYourLocations(); persistYourLocations(); */
setState(() {}); setState(() {});
}), }),
title: new Text(loc.description), title: new Text(loc.description),
@ -92,31 +124,31 @@ class _ActiveFiresPageState extends State<ActiveFiresPage> {
)); ));
} }
Widget _buildSavedLocations() { Widget _buildSavedLocations(List<YourLocation> yl, onDeleted, onToggle) {
return new ListView.builder( return new ListView.builder(
padding: const EdgeInsets.all(16.0), padding: const EdgeInsets.all(16.0),
itemCount: globals.yourLocations.length, itemCount: yl.length,
itemBuilder: (BuildContext _context, int i) { itemBuilder: (BuildContext _context, int i) {
return _buildItem(globals.yourLocations.elementAt(i)); return _buildItem(yl.elementAt(i), onDeleted, onToggle);
}); });
} }
void handleUndo(YourLocation item) { void handleUndo(YourLocation item) {
setState(() { setState(() {
/* FIXME
globals.yourLocations.add(item); globals.yourLocations.add(item);
persistYourLocations(); persistYourLocations(); */
}); });
} }
Widget _buildItem(YourLocation item) { Widget _buildItem(YourLocation item, onDelete, onToggle) {
final ThemeData theme = Theme.of(context); final ThemeData theme = Theme.of(context);
return new Dismissible( return new Dismissible(
key: new ObjectKey(item), key: new ObjectKey(item),
direction: DismissDirection.horizontal, direction: DismissDirection.horizontal,
onDismissed: (DismissDirection direction) { onDismissed: (DismissDirection direction) {
setState(() { setState(() {
globals.yourLocations.remove(item); onDelete(item.id);
persistYourLocations();
}); });
_scaffoldKey.currentState.showSnackBar(new SnackBar( _scaffoldKey.currentState.showSnackBar(new SnackBar(
@ -142,67 +174,89 @@ class _ActiveFiresPageState extends State<ActiveFiresPage> {
color: theme.canvasColor, color: theme.canvasColor,
border: new Border( border: new Border(
bottom: new BorderSide(color: theme.dividerColor))), bottom: new BorderSide(color: theme.dividerColor))),
child: _buildRow(item))); child: _buildRow(item, onToggle)));
} }
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
var hasLocations = globals.yourLocations.length > 0; return new StoreConnector<AppState, _ViewModel>(
final title = hasLocations distinct: false, // FIXME
? S.of(context).firesInYourPlaces converter: (store) {
: S.of(context).firesInTheWorld; return new _ViewModel(
print('Building Active Fires'); onAdd: (loc) {
return Scaffold( store.dispatch(new AddYourLocationAction(loc));
key: _scaffoldKey, },
// FIXME new? onDelete: (id) {
drawer: new MainDrawer(context), store.dispatch(new DeleteYourLocationAction(id));
appBar: new AppBar( },
title: Text(title), onToggleSubs: (id) {
leading: IconButton( store.dispatch(new ToggleSubscriptionAction(id));
icon: Icon(Icons.menu), },
onPressed: () { yourLocations: store.state.yourLocations);
_scaffoldKey.currentState.openDrawer(); },
}, builder: (context, view) {
), var hasLocations = view.yourLocations.length > 0;
), final title = hasLocations
floatingActionButtonLocation: FloatingActionButtonLocation.centerFloat, ? S.of(context).firesInYourPlaces
bottomNavigationBar: new GlobalFiresBottomStats(), : S.of(context).firesInTheWorld;
body: hasLocations print('Building Active Fires');
? new Stack(children: <Widget>[
_buildSavedLocations(), return Scaffold(
new FabDialer( key: _scaffoldKey,
_fabMiniMenuItemList(), fires600, new Icon(Icons.add)) // FIXME new?
]) drawer: new MainDrawer(context),
: new Center( appBar: new AppBar(
child: new CenteredColumn(children: <Widget>[ title: Text(title),
new RoundedBtn( leading: IconButton(
icon: Icons.location_searching, icon: Icon(Icons.menu),
text: 'Fires near your', onPressed: () {
onPressed: onAddYourLocation, _scaffoldKey.currentState.openDrawer();
backColor: fires600), },
const SizedBox(height: 26.0), ),
new RoundedBtn( ),
icon: Icons.edit_location, floatingActionButtonLocation:
text: S.of(context).firesNearPlace, FloatingActionButtonLocation.centerFloat,
onPressed: onAddOtherLocation, bottomNavigationBar: new GlobalFiresBottomStats(),
backColor: fires600), body: hasLocations
])), ? new Stack(children: <Widget>[
); _buildSavedLocations(
view.yourLocations, view.onDelete, view.onToggleSubs),
new FabDialer(_fabMiniMenuItemList(view.onAdd), fires600,
new Icon(Icons.add))
])
: new Center(
child: new CenteredColumn(children: <Widget>[
new RoundedBtn(
icon: Icons.location_searching,
text: 'Fires near your',
onPressed: () => onAddYourLocation(view.onAdd),
backColor: fires600),
const SizedBox(height: 26.0),
new RoundedBtn(
icon: Icons.edit_location,
text: S.of(context).firesNearPlace,
onPressed: () => onAddOtherLocation(view.onAdd),
backColor: fires600),
])),
);
});
} }
void onAddYourLocation() { void onAddYourLocation(AddYourLocationFunction onAdd) {
Future<YourLocation> location = getUserLocation(_scaffoldKey); Future<YourLocation> location = getUserLocation(_scaffoldKey);
_saveLocation(location); _saveLocation(location, onAdd);
} }
void onAddOtherLocation() { void onAddOtherLocation(AddYourLocationFunction onAdd) {
Future<YourLocation> location = openPlacesDialog(_scaffoldKey); Future<YourLocation> location = openPlacesDialog(_scaffoldKey);
_saveLocation(location); _saveLocation(location, onAdd);
} }
void _saveLocation(Future<YourLocation> location) { void _saveLocation(Future<YourLocation> location, onAdd) {
location.then((newLocation) { location.then((newLocation) {
if (newLocation != YourLocation.noLocation) { if (newLocation != YourLocation.noLocation) {
onAdd(newLocation);
/* FIXME
if (globals.yourLocations.contains(newLocation)) { if (globals.yourLocations.contains(newLocation)) {
showSnackMsg(S.of(context).addedThisLocation); showSnackMsg(S.of(context).addedThisLocation);
} else } else
@ -212,7 +266,7 @@ class _ActiveFiresPageState extends State<ActiveFiresPage> {
new Timer(new Duration(milliseconds: 1000), () { new Timer(new Duration(milliseconds: 1000), () {
showLocationMap(newLocation); showLocationMap(newLocation);
}); });
}); }); */
} }
}); });
} }

View file

@ -3,8 +3,6 @@ import 'package:redux/src/store.dart';
import 'models/appState.dart'; import 'models/appState.dart';
import 'redux/actions.dart'; import 'redux/actions.dart';
import 'globals.dart' as globals;
import 'models/firesApi.dart';
final FirebaseMessaging _firebaseMessaging = new FirebaseMessaging(); final FirebaseMessaging _firebaseMessaging = new FirebaseMessaging();

View file

@ -5,8 +5,6 @@ import 'package:get_it/get_it.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
import 'dart:async'; import 'dart:async';
import 'package:fires_flutter/models/yourLocation.dart';
// FIXME remove this later // FIXME remove this later
String gmapKey; String gmapKey;
String firesApiKey; String firesApiKey;
@ -18,6 +16,5 @@ final Widget appMediumIcon =
final Widget appIcon = final Widget appIcon =
Image.asset('images/logo-200.png', width: 24.0, height: 24.0); Image.asset('images/logo-200.png', width: 24.0, height: 24.0);
final Future<SharedPreferences> prefs = SharedPreferences.getInstance(); final Future<SharedPreferences> prefs = SharedPreferences.getInstance();
List<YourLocation> yourLocations = [];
final GetIt getIt = new GetIt(); final GetIt getIt = new GetIt();
bool isDevelopment = false; bool isDevelopment = false;

View file

@ -12,7 +12,7 @@ import 'models/firesApi.dart';
import 'redux/fetchDataMiddleware.dart'; import 'redux/fetchDataMiddleware.dart';
import 'redux/reducers.dart'; import 'redux/reducers.dart';
import 'package:fires_flutter/models/yourLocationPersist.dart'; import 'package:fires_flutter/models/yourLocationPersist.dart';
import 'package:redux_logging/redux_logging.dart';
Future<Map<String, dynamic>> loadSecrets() async { Future<Map<String, dynamic>> loadSecrets() async {
return await SecretLoader(secretPath: 'assets/private-settings.json').load(); return await SecretLoader(secretPath: 'assets/private-settings.json').load();
} }

View file

@ -1,9 +1,12 @@
import 'package:bson_objectid/bson_objectid.dart';
import 'package:comunes_flutter/comunes_flutter.dart';
import 'package:fires_flutter/models/yourLocation.dart';
import 'package:json_annotation/json_annotation.dart'; import 'package:json_annotation/json_annotation.dart';
import 'package:meta/meta.dart'; import 'package:meta/meta.dart';
import 'package:comunes_flutter/comunes_flutter.dart';
import 'fireMapState.dart'; import 'fireMapState.dart';
import 'yourLocation.dart';
import 'user.dart'; import 'user.dart';
part 'appState.g.dart'; part 'appState.g.dart';
@immutable @immutable
@ -32,8 +35,8 @@ class AppState extends Object with _$AppStateSerializerMixin {
_$AppStateFromJson(json); _$AppStateFromJson(json);
AppState( AppState(
{this.yourLocations : const <YourLocation>[], {this.yourLocations: const <YourLocation>[],
this.user: const User.initial(), this.user: const User.initial(),
this.isLoading: false, this.isLoading: false,
this.isLoaded: false, this.isLoaded: false,
this.error: null, this.error: null,
@ -66,6 +69,16 @@ class AppState extends Object with _$AppStateSerializerMixin {
@override @override
String toString() { String toString() {
return 'AppState{\nuser: ${user}\nisLoading: $isLoading\nisLoaded: $isLoaded\napiKey: ${ellipse(firesApiKey, 8)}\napiUrl: ${ellipse(firesApiUrl, 8)}\nyourLocations: ${yourLocations}'; return 'AppState{\nuser: ${user}\nisLoading: $isLoading\nisLoaded: $isLoaded\napiKey: ${ellipse(
firesApiKey, 8)}\napiUrl: ${ellipse(
firesApiUrl, 8)}\nyourLocations count: ${yourLocations
.length}\nyourLocations: ${yourLocations}';
} }
} }
typedef void AddYourLocationFunction(YourLocation loc);
typedef void DeleteYourLocationFunction(ObjectId id);
typedef void UpdateYourLocationFunction(ObjectId id, YourLocation loc);
typedef void ToggleSubscriptionFunction(ObjectId id);
typedef void SubscribeFunction(ObjectId id);
typedef void UnSubscribeFunction(ObjectId id);

View file

@ -4,8 +4,10 @@ import 'dart:convert';
import 'package:http/http.dart' as ht; import 'package:http/http.dart' as ht;
import 'package:jaguar_resty/jaguar_resty.dart' as resty; import 'package:jaguar_resty/jaguar_resty.dart' as resty;
import 'package:fires_flutter/models/yourLocation.dart';
import 'appState.dart'; import 'appState.dart';
import 'yourLocation.dart';
class FiresApi { class FiresApi {
FiresApi() { FiresApi() {

View file

@ -37,6 +37,8 @@ class YourLocation extends Object with _$YourLocationSerializerMixin {
if (this.id == null) this.id = new ObjectId(); if (this.id == null) this.id = new ObjectId();
} }
@override @override
bool operator ==(Object other) => bool operator ==(Object other) =>
identical(this, other) || identical(this, other) ||
@ -55,4 +57,10 @@ class YourLocation extends Object with _$YourLocationSerializerMixin {
lon.hashCode ^ lon.hashCode ^
description.hashCode ^ description.hashCode ^
subscribed.hashCode; subscribed.hashCode;
@override
String toString() {
return 'YourLocation {id: $id, lat: $lat, lon: $lon, description: $description, subscribed: $subscribed}';
}
} }

View file

@ -1,11 +1,12 @@
import 'dart:convert';
import '../globals.dart' as globals;
import 'dart:async'; import 'dart:async';
import 'yourLocation.dart'; import 'dart:convert';
import 'package:fires_flutter/models/yourLocation.dart';
import 'package:shared_preferences/shared_preferences.dart'; import 'package:shared_preferences/shared_preferences.dart';
final String locationKey = 'yourlocations'; import '../globals.dart' as globals;
final String locationKey = 'yourlocations';
Future<List<YourLocation>> loadYourLocations() async { Future<List<YourLocation>> loadYourLocations() async {
return await globals.prefs.then((prefs) { return await globals.prefs.then((prefs) {
@ -23,7 +24,8 @@ persistYourLocations(List<YourLocation> yl) {
}); });
} }
Future<List<YourLocation>> loadYourLocationsWithPrefs(SharedPreferences prefs) async { Future<List<YourLocation>> loadYourLocationsWithPrefs(
SharedPreferences prefs) async {
return await globals.prefs.then((prefs) { return await globals.prefs.then((prefs) {
List<String> yourLocations = prefs.getStringList(locationKey); List<String> yourLocations = prefs.getStringList(locationKey);
if (yourLocations == null) { if (yourLocations == null) {
@ -33,9 +35,8 @@ Future<List<YourLocation>> loadYourLocationsWithPrefs(SharedPreferences prefs) a
List<YourLocation> persistedList = List<YourLocation>(); List<YourLocation> persistedList = List<YourLocation>();
yourLocations.forEach((locationString) { yourLocations.forEach((locationString) {
Map locationMap = json.decode(locationString); Map locationMap = json.decode(locationString);
persistedList.add(YourLocation.fromJson(locationMap)); persistedList.add(YourLocation.fromJson(locationMap));
}); });
return persistedList; return persistedList;
}); });
} }

View file

@ -1,4 +1,4 @@
import '../models/yourLocation.dart'; import 'package:fires_flutter/models/yourLocation.dart';
abstract class AppActions {} abstract class AppActions {}
@ -32,4 +32,4 @@ class OnUserLangAction extends AppActions {
final String lang; final String lang;
OnUserLangAction(this.lang); OnUserLangAction(this.lang);
} }

View file

@ -3,7 +3,9 @@ import 'package:redux/redux.dart';
import '../globals.dart' as globals; import '../globals.dart' as globals;
import '../models/appState.dart'; import '../models/appState.dart';
import '../models/firesApi.dart'; import '../models/firesApi.dart';
import '../models/yourLocation.dart';
import 'package:fires_flutter/models/yourLocation.dart';
import '../models/yourLocationPersist.dart'; import '../models/yourLocationPersist.dart';
import 'actions.dart'; import 'actions.dart';

View file

@ -1,3 +1,6 @@
import 'actions.dart';
bool loadedReducer(isLoaded, action) { bool loadedReducer(isLoaded, action) {
if (action is FetchYourLocationsSucceededAction) return true;
return isLoaded; return isLoaded;
} }

View file

@ -1,3 +1,5 @@
import 'actions.dart';
bool loadingReducer(isLoading, action) { bool loadingReducer(isLoading, action) {
if (action is FetchYourLocationsAction) return true;
return isLoading; return isLoading;
} }

View file

@ -1,6 +1,7 @@
import 'package:bson_objectid/bson_objectid.dart'; import 'package:bson_objectid/bson_objectid.dart';
import 'package:fires_flutter/models/yourLocation.dart';
import '../models/yourLocation.dart';
abstract class YourLocationActions {} abstract class YourLocationActions {}
@ -12,6 +13,7 @@ class AddYourLocationAction extends YourLocationActions {
class DeleteYourLocationAction extends YourLocationActions { class DeleteYourLocationAction extends YourLocationActions {
ObjectId id; ObjectId id;
DeleteYourLocationAction(this.id); DeleteYourLocationAction(this.id);
} }

View file

@ -1,6 +1,6 @@
import 'package:fires_flutter/models/yourLocation.dart';
import 'package:redux/redux.dart'; import 'package:redux/redux.dart';
import '../models/yourLocation.dart';
import 'actions.dart'; import 'actions.dart';
final yourLocationsReducer = combineReducers<List<YourLocation>>([ final yourLocationsReducer = combineReducers<List<YourLocation>>([