Home > Software design >  How does the onPressed voidcallback change the boolean in my function?
How does the onPressed voidcallback change the boolean in my function?

Time:09-21

Situation:

I have a checkbox in one place and i am sending the callback etc. up the widget tree to run a setState and run the function applyFilters().

The NeededChecked is also routed up to the checkbox-value.

Question:

What i am struggling to understand is why this works.

Specifically how the onPressed callback is able to set the value of the bool isNeededState to true/false?

Here is the code that is run. The only important part is the passing of the bool isNeededState to the neededCheked.

 void neededFilterCalled(bool isNeededState) {
    setState(() {
      NeededChecked = isNeededState;
      applyFilters();
    });
}

And here is the checkbox widget:

Widget build(BuildContext context) {
  return Checkbox(
    value: isNeededChecked,
    onChanged: neededFilterCalled,
  );
}

CodePudding user response:

Writing

onChanged: neededFilterCalled,

is shorthand for

onChanged: (value) => neededFilterCalled(value),

CodePudding user response:

onChanged provide nullable bool, defined as

required void Function(bool?)? onChanged

You can accept null value and provide false on null case like

  void neededFilterCalled(bool? isNeededState) {
    setState(() {
      isNeededChecked = isNeededState ?? false;
      applyFilters();
    });
  }
return Checkbox(
  value: isNeededChecked,
  onChanged: neededFilterCalled,
);
  • Related