Flutter error: A value of type 'Object?' can't be assigned to a variable of type 'String'
20,176
Solution 1
Assign the generic type String
to the DropdownButtonFormField:
DropdownButtonFormField<String>(
value: _currentSugars,
decoration: textInputDecoration,
items: sugars.map((sugar) {
return DropdownMenuItem(
value: sugar,
child: Text('$sugar sugars'),
);
}).toList(),
onChanged: (val) => setState(() => _currentSugars = val),
),
Unless you specify the type String
dart makes the assumption with the one of the most generic types it has Object?
as the generic type of the DropdownButtonFormField
Complete demo (Updated to use null safety)
class Demo extends StatefulWidget {
Demo({Key? key}) : super(key: key);
@override
_DemoState createState() => _DemoState();
}
class _DemoState extends State<Demo> {
final sugars = ['candy', 'chocolate', 'snicker'];
String? _currentSugars = 'candy';
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: DropdownButtonFormField<String>(
value: _currentSugars,
items: sugars.map((sugar) {
return DropdownMenuItem(
value: sugar,
child: Text('$sugar sugars'),
);
}).toList(),
onChanged: (val) => setState(() => _currentSugars = val),
),
),
);
}
}
Solution 2
Try to give val
as a String, or any type you want to to become:
onChanged: (val) => setState(() => _currentSugars = val as String),
Related videos on Youtube
Author by
Mike Osborn
Updated on January 26, 2022Comments
-
Mike Osborn about 2 years
I am using a dropdownbuttonfield and getting this error:
A value of type 'Object?' can't be assigned to a variable of type 'String'. Try changing the type of the variable, or casting the right-hand type to 'String'.dart(invalid_assignment)
Code :
class SettingsForm extends StatefulWidget { @override _SettingsFormState createState() => _SettingsFormState(); } class _SettingsFormState extends State<SettingsForm> { final _formKey = GlobalKey<FormState>(); final List<String> sugars = ['0', '1', '2', '3', '4']; final List<int> strengths = [100, 200, 300, 400, 500, 600, 700, 800, 900]; // form values String? _currentName; String? _currentSugars; int? _currentStrength; @override Widget build(BuildContext context) { MyUser user = Provider.of<MyUser>(context); return StreamBuilder<UserData>( stream: DatabaseService(uid: user.uid).userData, builder: (context, snapshot) { if (snapshot.hasData) { UserData? userData = snapshot.data; return Form( key: _formKey, child: Column( children: <Widget>[ Text( 'Update your brew settings.', style: TextStyle(fontSize: 18.0), ), SizedBox(height: 20.0), TextFormField( initialValue: userData!.name, decoration: textInputDecoration, validator: (val) => val!.isEmpty ? 'Please enter a name' : null, onChanged: (val) => setState(() => _currentName = val), ), SizedBox(height: 10.0), DropdownButtonFormField( value: _currentSugars ?? userData.sugars, decoration: textInputDecoration, items: sugars.map((sugar) { return DropdownMenuItem( value: sugar, child: Text('$sugar sugars'), ); }).toList(), onChanged: (val) => setState(() => _currentSugars = val), <--Error here **val** right one ), SizedBox(height: 10.0), Slider( value: (_currentStrength ?? userData.strength).toDouble(), activeColor: Colors.brown[_currentStrength ?? userData.strength], inactiveColor: Colors.brown[_currentStrength ?? userData.strength], min: 100.0, max: 900.0, divisions: 8, onChanged: (val) => setState(() => _currentStrength = val.round()), ), ElevatedButton( style: ElevatedButton.styleFrom(primary: Colors.pink[400]), child: Text( 'Update', style: TextStyle(color: Colors.white), ), onPressed: () async { if (_formKey.currentState!.validate()) { await DatabaseService(uid: user.uid).updateUserData( _currentSugars ?? snapshot.data!.sugars, _currentName ?? snapshot.data!.name, _currentStrength ?? snapshot.data!.strength); Navigator.pop(context); } }), ], ), ); } else { return Loading(); } }); } }
Update Update 2 A value of type 'String?' can't be assigned to a variable of type 'String'. Try changing the type of the variable, or casting the right-hand type to 'String'.
-
TheAlphamerc over 2 yearspls do mention the type of
_currentSugars
andsugars
. -
Mike Osborn over 2 years@TheAlphamerc they are both 'Strings'
-
Midhun MP over 2 years@MikeOsborn Just set
_currentSugars = val!
-
Mike Osborn over 2 years@MidhunMP the error doesn't change
-
Mike Osborn over 2 yearsdo you want an update screenshot?
-
Midhun MP over 2 years@MikeOsborn What is the error you are getting now?
-
Mike Osborn over 2 years@MidhunMP same error I have two 'val' and they are both objects and I think they should both be 'strings' and dynamic
-
Midhun MP over 2 years@MikeOsborn My above comment is for your current screenshot and for the error
'String?' can't be assigned to a variable of type 'String'
-
Mike Osborn over 2 yearsno it's not the same code
-
Mike Osborn over 2 years@MidhunMP pls see the update 2 screenshot
-
Midhun MP over 2 yearsYou need to change
DropdownButtonFormField
toDropdownButtonFormField<String>
then use my above mentioned comment -
Mike Osborn over 2 yearsWait I didn't have to put the exclamation mark, it worked just by putting "<String> but since you solved my previous problem by "String? _currentSugars;" it now works without null check.
-
Midhun MP over 2 years@MikeOsborn Yeah, since you declared it as nullable, so you no longer need to use !.
-
Mike Osborn over 2 years@MidhunMP Can u solve this q also stackoverflow.com/questions/68460812/… Thanks in advance
-
-
croxx5f over 2 yearsIt does work for me, I added a demo in which I declare both
_currentSugars
andsugars
which are the only to unknowns to me from the code you posted -
croxx5f over 2 yearsupdated it. I forgot about null safety 😅
-
Mike Osborn over 2 yearscan you tell the difference and see what's causing the error