The argument type 'void Function(String)' can't be assigned to the parameter type 'void Function(String?)?' in DropdownButton
The error you get came from null-safety, the type String?
means that it could be either a String
, or null
, but your parameter only accepts a String
, and no null
.
For this, you can "force" the use of 'non-null' variable by adding a ! at the end of your variable, but be careful when doing this.
onChanged: (String? userchoice){
setState(() {
this._currentGadgets = userchoice;
});
},
You can learn more about null-safety syntax and principles on the official documentation: https://flutter.dev/docs/null-safety.
https://api.flutter.dev/flutter/material/DropdownButton-class.html.
Roshan Ojha
Updated on December 30, 2022Comments
-
Roshan Ojha over 1 year
I am trying to add DropdownButton widget to my app.
This is code for my app
import 'package:flutter/material.dart'; void main() { runApp(MaterialApp( home: Home(), )); } class Home extends StatefulWidget { @override _HomeState createState() => _HomeState(); } class _HomeState extends State<Home> { var gadgets = ['Laptop', 'Cell-phone', 'Drone', 'earbuds', 'walkman']; var _currentGadgets = 'Gadgets'; @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text('Dropdown Button'), centerTitle: true, ), body: Column( children: [ DropdownButton( items: gadgets.map((e){ return DropdownMenuItem( value: e, child: Text(e), ); }).toList(), onChanged: (String userchoice){ setState(() { this._currentGadgets = userchoice; }); }, value: _currentGadgets, ), ], ), ); } }
When I try to execute this code this error appears
The argument type 'void Function(String)' can't be assigned to the parameter type 'void Function(String?)?'.
How can I solve this problem? I am new to flutter, I am stucked in this code from past 2 days. Please help.