Home > Enterprise >  How can i check on null?
How can i check on null?

Time:05-05

I have void func:

//change state in select
    void _onChangeSelect(Color? newValue) {
      setState(() {
        _selectedValue = newValue!;
      });
    }

How can I check for null without "!", but with "??".

CodePudding user response:

you need to provide a fallback then, a color to use when it is null. for example

//change state in select
    void _onChangeSelect(Color? newValue) {
      setState(() {
        _selectedValue = newValue ?? Colors.white;
      });
    }

or if you want to keep the old value

//change state in select
    void _onChangeSelect(Color? newValue) {
      setState(() {
        _selectedValue = newValue ?? _selectedValue ;
      });
    }

or simply write this

//change state in select
    void _onChangeSelect(Color? newValue) {
      setState(() {
        if (newValue != null) {
          _selectedValue = newValue;
        }
      });
    }
  • Related