I’m using Flutter bloc cubit and equatable to manage a simple form. in the birthday field, i check if it’s a valid date and then send it to bloc and works fine. but if user then changes the date i want to make the birthday field null in my bloc, but it just doesn’t emit when i send a null value to it.
this is my cubit state
class RegistrationState extends Equatable {
final DateTime? birthday;
final String email;
final String password;
const RegistrationState({
this.birthday,
this.email = '',
this.password = '',
});
RegistrationState copyWith({
DateTime? birthday,
String? email,
String? password,
}) {
return RegistrationState(
birthday: birthday ?? this.birthday,
specialty: specialty ?? this.specialty,
email: email ?? this.email,
);
}
@override
List<Object?> get props => [
birthday,
email,
password,
];
}
and this is my function inside cubit
void updateBirthday(DateTime? birthday) {
emit(state.copyWith(birthday: birthday));
}
as I said, it works fine when I send DateTime values, but if I send null values it just doesn’t emit anything
2
Answers
Tanks to Md. Yeasin Sheikh, i found a solution using ValueGetter, just updating the value inside copyWith methos like this
and then just calling it from cubit function like this
Ahh yes, you’ve discovered the typical problem with copyWith: you cannot "update" a value with a null, because a null value is the same as the parameter not being present (usually). Therefore, copyWith returns a clone of the original object, which will not trigger an event in cubit because two "equal" events are never emitted in a row.