Home > Software engineering >  how to pass uncertain parameter to methode flutter
how to pass uncertain parameter to methode flutter

Time:01-29

I have a methode like followings:

  void reverseWeekdayStatus({alarmClock,sundayIsSelected}){
    alarmClock.sundayIsSelected = !alarmClock.sundayIsSelected ?? false;
    update();
  }

alarmClock is a model:

class AlarmClock {
  bool sundayIsSelected;
  bool mondayIsSelected;
  bool tuesdaySelected;
  bool wednesdayIsSelected;
  bool thursdayIsSelected;
  bool fridayIsSelected;
  bool saturdayIsSelected;

  AlarmClock({
    this.sundayIsSelected = false,
    this.mondayIsSelected = false,
    this.tuesdaySelected = false,
    this.wednesdayIsSelected = false,
    this.thursdayIsSelected = false,
    this.fridayIsSelected = false,
    this.saturdayIsSelected = false,
  });
}

so for this methode I want to not just sundayIsSelected also the rest like mondayIsSelected could be reversed if I implement this methode, what I did is followings:

  void reverseWeekdayStatus({alarmClock,whichDay}){
    alarmClock.whichDay = !alarmClock.whichDay ?? false;
    update();
  }

And pass mondayIsSelected for example to whichDay, and then I got an error since whichDay does not existed in alarmClock, another way I thought is to create separately methodes like from monday to sunday, is there a smarter way to do this job? thanks!

CodePudding user response:

class AlarmClock {
  bool sundayIsSelected;

  AlarmClock({
    this.sundayIsSelected = false,
  });
}

On current mode, you are providing default for each field. If you don't pass any value for sundayIsSelected it will get default value false. But sundayIsSelected is not nullable. It can't be null.

Therefore, alarmClock.sundayIsSelected ?? false will never get false.

To reverse, you just like to change the value then do

 void reverseWeekdayStatus({
    alarmClock,
  }) {
    alarmClock.sundayIsSelected = !alarmClock.sundayIsSelected;
   ...
  }

It will switch the bool when ever gets call. You can do conditional state on update case, and it is an optional parameter with default value.

void reverseWeekdayStatus({alarmClock, bool switchSundayState = false}) {
  if (switchSundayState) {
    alarmClock.sundayIsSelected = !alarmClock.sundayIsSelected;
  }
}

Another technic is using copyWith constructor, it is nullable (optional) named constructor, use current value if we don't pass value for field.

class AlarmClock {
  final bool sundayIsSelected;

  AlarmClock({
    this.sundayIsSelected = false,
  });

  AlarmClock copyWith({
    bool? sundayIsSelected,
  }) {
    return AlarmClock(
      sundayIsSelected: sundayIsSelected ?? this.sundayIsSelected,
    );
  }
}

And use cases

alarmClock = alarmClock.copyWith(sundayIsSelected: true);

  •  Tags:  
  • Related