skip to Main Content

im trying to make a dropdownbutton has elements from my database (mysql) and im getting this error
A value of type 'Object?' can't be assigned to a variable of type 'String?'.
this is my code :

String? selectedCategory;
  List categoryItem=[];
....
 DropdownButton(
           value: selectedCategory,
            hint: Text('Select category'),
            items: categoryItem.map((category) {
              return DropdownMenuItem(
                value: category['name'],
                  child: Text(category['name']));
            }).toList(),
            onChanged: ( value){
              setState(() {
                selectedCategory=value;
              });
            },
            isExpanded: true,

        ),

the problem exactly here :

onChanged: ( value){
              setState(() {
                selectedCategory=value;
              });

i tried this :

 onChanged: (String? newValue) {
    setState(() {
      selectedCategory = newValue!;
    });

and didnt work

3

Answers


  1. Change

    setState(() {
       selectedCategory=value;
    });
    

    to

    setState(() {
       selectedCategory = value as String?;
    });
    
    Login or Signup to reply.
  2. Issue is just that its not setting the value as string. You need to parse the value as String and its good to go.

    You can parse the object to string by many ways.

    1. selectedCategory = value as String?
    2. selectedCategory = value?+""
    3. selectedCategory = value?.toString()
    Login or Signup to reply.
  3. To fix this, you need to explicitly cast the value to String? in the onChanged callback. Here’s how you can do it:

    onChanged: (dynamic value) { // Use dynamic type for value
      setState(() {
        selectedCategory = value as String?; // Cast value to String?
      });
    },
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search