Created
September 28, 2020 21:00
-
-
Save rodydavis/f45591bc23e996b946652ee0e722b760 to your computer and use it in GitHub Desktop.
Dart + Bloc + Freezed (Unions and Map to State)
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:bloc/bloc.dart'; | |
import 'package:freezed_annotation/freezed_annotation.dart'; | |
part 'counter_bloc.freezed.dart'; | |
class CounterBloc extends Bloc<CounterEvent, CounterState> { | |
CounterBloc() : super(CounterState.value(0)); | |
@override | |
Stream<CounterState> mapEventToState(CounterEvent event) async* { | |
yield* event.map<Stream<CounterState>>( | |
increment: (val) async* { | |
yield CounterState.value(state.value + 1); | |
}, | |
decrement: (val) async* { | |
yield CounterState.value(state.value - 1); | |
}, | |
update: (val) async* { | |
yield CounterState.value(val.value); | |
}, | |
reset: (val) async* { | |
yield CounterState.value(0); | |
}, | |
); | |
} | |
} | |
@freezed | |
abstract class CounterEvent with _$CounterEvent { | |
const factory CounterEvent.decrement() = CounterDecrement; | |
const factory CounterEvent.increment() = CounterIncrement; | |
const factory CounterEvent.update(int value) = CounterUpdate; | |
const factory CounterEvent.reset() = CounterReset; | |
} | |
@freezed | |
abstract class CounterState with _$CounterState { | |
const factory CounterState.value(int value) = CounterReady; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment