Skip to content

Instantly share code, notes, and snippets.

@rodydavis
Created September 28, 2020 21:00
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 rodydavis/f45591bc23e996b946652ee0e722b760 to your computer and use it in GitHub Desktop.
Save rodydavis/f45591bc23e996b946652ee0e722b760 to your computer and use it in GitHub Desktop.
Dart + Bloc + Freezed (Unions and Map to State)
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