Last active
April 14, 2020 19:07
-
-
Save chimon2000/69cfeb5f55e582d65ce311e3f8fa50bd to your computer and use it in GitHub Desktop.
Reducer with State Notifier
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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); | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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