Why do we need to use the Equatable class with flutter_bloc
? Also, what do we use the props for? Below is sample code for making a state using the bloc pattern in Flutter.
abstract class LoginStates extends Equatable{}
class LoginInitialState extends LoginStates{
@override
List<Object> get props => [];
}
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
}