skip to Main Content

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


  1. Chosen as BEST ANSWER

    Tanks to Md. Yeasin Sheikh, i found a solution using ValueGetter, just updating the value inside copyWith methos like this

    RegistrationState copyWith({
    //change this
    ValueGetter<DateTime?>? birthday, 
    String? email,
    String? password,
    }) {  
        return RegistrationState(
            //and this
            birthday: birthday != null ? birthday() : this.birthday
            specialty: specialty ?? this.specialty,
            email: email ?? this.email,
        ); 
    }
    

    and then just calling it from cubit function like this

    void updateBirthday(DateTime? birthday) {
        emit(state.copyWith(birthday: () => birthday));
    }
    

  2. void updateBirthday(DateTime? birthday) {
      emit(state.copyWith(birthday: birthday));
    
    }
    

    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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search