How to deal with null parameters in ui event handlers where null makes no sense

Viewed 38

Before I updated my dart version to support only non-null that code was working fine:

Radio(
              value: ExcerciseType.weight,
              groupValue: type,
              onChanged: (ExcerciseType value) {
                appState.exerciseType = value;
              },
            ),

Now the compiler complaints:

"The argument type 'void Function(ExcerciseType)' can't be assigned to the parameter type 'void Function(ExcerciseType?)?'.",

This would fix it:

 onChanged: (ExcerciseType? value) {
                    appState.exerciseType = value as ExcerciseType;
      },

but that fix is not logical at all. With the as cast I just say value might be null at runtime and appState.exerciseType can accept null values but that is not true at all! appState.ExerciseType is of type ExcerciseType and not ExcerciseType?.

What do I not understand here?

1 Answers

onChanged: (ExcerciseType value){} means you will get non-nullable value. But

onChanged: (ExcerciseType? value){} means you will receive nullable ExcerciseType date.

The default onChanged: provide nullable data.

ValueChanged<T?>? onChanged

We can have nullable radio button, means it will actually return null after selecting one. And it is useful for some cases. This snippet show you can have null as return. Here, 1st radio button will return null.

 int? value;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: Column(
          children: List.generate(
        5,
        (index) => Radio<int?>(
          value: index == 0 ? null : index,
          groupValue: value,
          onChanged: (int? v) {
            print(v);
            setState(() {
              value = v;
            });
          },
        ),
      )),
    );
  }
}

You can directly use ! if you're certain about non-nullable data.

Radio<ExcerciseType>(  
     onChanged: (ExcerciseType? value) {
      appState.exerciseType = value!;      
     }
   )

More about onChanged and null-safety

Related