Nullable
Nullable

Reputation: 984

BlocBuilder cannot listen to all state changes

I'm practicing with flutter bloc and I'm getting used to using BlocBuilder. I understand it can listen to all state changes and I can update widgets easily. Everything was going well until I hit the emit state twice in a row and I ran into a problem.

I emit state several times in a row, and I only get the last state in BlocBuilder, which is completely different from what I expected.

Below is the code of my bloc.dart:

   emit(state.copyWith(testText: "1"));
   emit(state.copyWith(testText: "2"));
   emit(state.copyWith(testText: "3"));
   emit(state.copyWith(testText: "4"));
  1. Use BlocBuilder to listen to the state:
@override
  Widget build(BuildContext context) {
    return BlocBuilder<TestBloc, TestState>(
      buildWhen: (previous, current) => previous.testText != current.testText,
      builder: (context, state) {
        print("state.testText builder>>> ${state.testText}");
        return Center();
      },
    );
  }

The result of the output. I expected to get 1, 2, 3, 4, but only 4.

flutter: state.testText builder>>> 4
  1. Use BlocConsumer to listen to the state:
@override
  Widget build(BuildContext context) {
    return BlocConsumer<TestBloc, TestState>(
      listenWhen: (previous, current) => previous.testText != current.testText,
      listener: (context, state) {
        print("state.testText listener >>> ${state.testText}");
      },
      buildWhen: (previous, current) => previous.testText != current.testText,
      builder: (context, state) {
        print("state.testText builder>>> ${state.testText}");
        return Center();
      },
    );
  }

The result of the output. The listener fully meets my expectations, but this is different from what I understand. The listener I understand is only responsible for updating loading, dialog, etc.

flutter: state.testText listener >>> 1
flutter: state.testText listener >>> 2
flutter: state.testText listener >>> 3
flutter: state.testText listener >>> 4
flutter: state.testText builder>>> 4

I wonder why BlocBuilder can't listen to all state? When to use BlocBuilder and when to use BlocListener? In order not to miss state, do I need to replace it with BlocListener?

Is BlocBuilder optimized? In order to avoid building widgets frequently, is the state obtained only once per runloop?

Upvotes: 0

Views: 1298

Answers (1)

Mehmet Demir
Mehmet Demir

Reputation: 283

Please add await 100 milliseconds between emit methods.

Maybe you're changing the state too quickly. Maybe you're changing the situation too quickly. If Flutter draws the screen in 1 ms, you are changing the state from 1 to 4 in 0.5ms. you are changing the state from 1 to 4 in 0.5 ms.

Upvotes: 1

Related Questions