Skip to content

Instantly share code, notes, and snippets.

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