Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
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> {
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