Skip to content

Instantly share code, notes, and snippets.

@parse-code
Last active June 18, 2019 08:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save parse-code/9b8eafcc6a8b60eb99f21c4a5632f901 to your computer and use it in GitHub Desktop.
Save parse-code/9b8eafcc6a8b60eb99f21c4a5632f901 to your computer and use it in GitHub Desktop.
[Flutter redux] #Flutter #Redux
import 'package:flutter/material.dart';
import 'package:flutter_redux/flutter_redux.dart';
import 'package:redux/redux.dart';
enum Actions { Increment, Decrement, Reset }
class AppState {
final int count;
AppState({this.count = 0});
}
AppState counterReducer(AppState state, action) {
if (action == Actions.Increment) {
return new AppState(count: state.count + 1);
} else if (action == Actions.Decrement) {
return new AppState(count: state.count - 1);
} else if (action == Actions.Reset) {
return new AppState(count: 0);
}
return state;
}
void main() {
final store = new Store(counterReducer, initialState: new AppState(count: 0));
runApp(new CounterApp(store: store));
}
class CounterApp extends StatelessWidget {
final Store<AppState> store;
CounterApp({Key key, this.store}) : super(key: key);
@override
Widget build(BuildContext context) {
return new StoreProvider(
store: store,
child: new MaterialApp(
home: new Scaffold(
body: new Center(
child: StoreConnector<AppState, Store>(
builder: (context, _store) {
return GestureDetector(
child: Text(
_store.state.count.toString(),
style: TextStyle(
fontSize: 30,
),
),
onTap: () => _store.dispatch(Actions.Decrement),
onDoubleTap: () => _store.dispatch(Actions.Reset),
onLongPress: () => _store.dispatch(Actions.Reset),
);
},
converter: (store) {
return store;
},
),
),
floatingActionButton: new StoreConnector<AppState, VoidCallback>(
builder: (context, callback) {
return new FloatingActionButton(
onPressed: callback,
child: Icon(Icons.add),
);
}, converter: (store) {
return () => store.dispatch(Actions.Increment);
}),
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment