Skip to content

Instantly share code, notes, and snippets.

@chimon2000
Last active April 14, 2020 19:07
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 chimon2000/69cfeb5f55e582d65ce311e3f8fa50bd to your computer and use it in GitHub Desktop.
Save chimon2000/69cfeb5f55e582d65ce311e3f8fa50bd to your computer and use it in GitHub Desktop.
Reducer with State Notifier
import 'dart:async';
import 'package:state_notifier/state_notifier.dart';
class ReducerNotifier<State> extends StateNotifier<State> {
final Reducer<State> reducer;
ReducerNotifier(state, this.reducer) : super(state);
FutureOr<void> dispatch(Action action) async {
state = await reducer.reduce(state, action);
}
}
abstract class Action {}
abstract class Reducer<State> {
FutureOr<State> reduce(State state, Action action);
}
import 'package:flutter_test/flutter_test.dart';
import 'package:reducer_notifier/reducer_notifier.dart';
void main() {
test('adds one to input values', () async {
final counter = ReducerNotifier(0, CounterReducer());
await counter.dispatch(IncrementAction());
expect(counter.debugState, 1);
await counter.dispatch(IncrementAction());
expect(counter.debugState, 2);
await counter.dispatch(DecrementAction());
expect(counter.debugState, 1);
});
}
class IncrementAction extends Action {}
class DecrementAction extends Action {}
class CounterReducer extends Reducer<int> {
@override
reduce(state, Action action) {
if (action is IncrementAction) return state + 1;
if (action is DecrementAction) return state - 1;
return state;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment