Skip to content

Using Stream for counter maybe too complicated for beginning. #2

@killvung

Description

@killvung

So using StreamController to store the count state and display it with StreamBuilder and AsyncSnapshot in the UI are really complicated for Flutter beginner without BloC experience. For me I would simply storing the count state as an int and registering events under the bloc class with on instead of mapping them, then display it with context
For example

class CounterBloc extends Bloc<CounterEvent, CounterState> {
  CounterBloc() : super(const Counter(0)) {
    on<CounterIncrementPressed>(
        (event, emit) => emit(Counter(state.count + 1)));
    on<CounterDecrementPressed>(
        (event, emit) => emit(Counter(state.count - 1)));

    on<CounterResetPressed>((event, emit) => emit(const Counter(0)));
  }
}

Then in UI

body: Center(
        child: BlocBuilder<CounterBloc, int>(
          builder: (context, count) {
            return Text('$count', style: textTheme.headline2);
          },
        ),
      ),

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions