-1

I started seeing this error in my DropdownButton after migrating to null safety.

DropdownButton<String>(
  value: myValue,
  onChanged: (String string) { // Error
    print(string);
  },
  items: [
    DropdownMenuItem(
      value: 'foo',
      child: Text('Foo'),
    ),
    DropdownMenuItem(
      value: 'bar',
      child: Text('Bar'),
    ),
  ],
)

Error:

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

iDecode
  • 22,623
  • 19
  • 99
  • 186

1 Answers1

1

Check the implementation of value property, it is nullable.

final T? value;

That means you can provide String? to the value and if you're providing String? should the onChanged not return String?.

To answer your question:

Change the type of onChanged method from String to String? like this:

onChanged: (String? string) { 
  print(string);
}

or, just omit the type String? and let Dart infer it for you.

onChanged: (string) { 
  print(string);
}
iDecode
  • 22,623
  • 19
  • 99
  • 186