Single mutable state instead of multiple immutable states?

Issue

I’m using the library flutter_bloc v 6.0.0. I’m looking for the correct way to use a single mutable object that holds multiple states.

For example, instead of multiple states:

enum RaisedButtonState {
  loading, idle
}
enum FlatButtonState {
  loading, idle
}

I want to use a single state object:

class MyState {
  bool raisedButtonLoading;
  bool flatButtonLoading;
  MyState({
    this.flatButtonLoading = false,
    this.raisedButtonLoading = false,
  });
}

However, this will have issue when emitting a new event using the same state, eg

emit(this.state..raisedButtonLoading = false);

because the emit() function has a validation to check for identical states

if (state == _state && _emitted) return;

Currently to workaround, I added the following to MyState:

@override
int get hashCode => super.hashCode;

@override
bool operator ==(Object o) {
  return false;
}

I understand this may violate the core concept of the library. However, having to create a separate enum/class for different states seems a little redundant especially in a project I’m currently working on which has a complex UI structure.

Wondering if there’s a better or correct way to achieve this?

Solution

You should not just return false in your operator ==. If a state being equal means the two bools are equal, then program it that way.

Apart from that, there is no Bloc police to come and get you if you only have one state that has many variables. I would still think about making that state immutable and generating a new state every time, even if it’s the same class. You could take a hint from the core classes and have a copyWith method like ThemeData to make it easy to create new states.

Answered By – nvoigt

Answer Checked By – Jay B. (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *