using Equatable class with flutter_bloc

Issue

why when we need to use Equatable class with flutter_bloc? , and also what about the props, for what we need it? this is a sample code for make a state in bloc pattern in flutter, please i need a detailed answer. thank you in advance

abstract class LoginStates extends Equatable{}

class LoginInitialState extends LoginStates{
  @override
  List<Object> get props => [];

}

Solution

For comparison of data, we required Equatable. it overrides == and hashCode internally, which saves a lot of boilerplate code. In Bloc, we have to extend Equatable to States and Events classes to use this functionality.

 abstract class LoginStates extends Equatable{}

So, that means LoginStates will not make duplicate calls and will not going to rebuild the widget if the same state occurs.

Define State:

class LoginInitialState extends LoginStates {}

Define State with props:

props declared when we want State to be compared against the values which declared inside props List

class LoginData extends LoginStates {
  final bool status;
  final String userName;
  const LoginData({this.status, this.userName});
  @override
  List<Object> get props => [this.status, this.userName];
}

If we remove the username from the list and keep a list like [this.status], then State will only consider the status field, avoiding the username field. That is why we used props for handling State changes.

Bloc Stream Usage:

As we extending State with Equatable that makes a comparison of old state data with new state data. As an example let’s look at the below example here LoginData will build a widget only once, which will avoid the second call as it is duplicated.

@override
Stream<LoginStates> mapEventToState(MyEvent event) async* {
  yield LoginData(true, 'Hello User');
  yield LoginData(true, 'Hello User'); // This will be avoided
}

Detail Blog: https://medium.com/flutterworld/flutter-equatable-its-use-inside-bloc-7d14f3b5479b

Answered By – Jitesh Mohite

Answer Checked By – Marie Seifert (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.