Home > Back-end >  A value of type 'Object?' can't be assigned to a variable of type 'String'
A value of type 'Object?' can't be assigned to a variable of type 'String'

Time:09-28

DropdownButton(
                value: dropdownvalue,
                icon: Icon(Icons.keyboard_arrow_down),
                items:items.map((String items) {
                  return DropdownMenuItem(
                      value: items,
                      child: Text(items)
                  );
                }
                ).toList(),
                onChanged: (Object? newValue) async {
                  setState(() {
                    dropdownvalue = newValue;
                  }
                  );
                },
              ),

CodePudding user response:

According to the documentation, the field value for the DropDownButton widget is of type final T?. This means that it is a generic type that can also be nullable.

Since you did not provide a more inclusive example of your code, I am assuming from the error, that the variable dropdownvalue was declared of type String.

You can remedy the situation in this manner:

DropdownButton**<String>**(
                value: dropdownvalue,
                icon: Icon(Icons.keyboard_arrow_down),
                items:items.map((String items) {
                  return DropdownMenuItem(
                      value: items,
                      child: Text(items)
                  );
                }
                ).toList(),
                onChanged: (**String** newValue) async {
                  setState(() {
                    dropdownvalue = newValue;
                  }
                  );
                },
              ),

CodePudding user response:

Try it like that as specified in mooner's answer.

DropdownButton<String>(
  value: dropdownvalue,
  icon: Icon(Icons.keyboard_arrow_down),
  items: items.map((items) {
    return DropdownMenuItem(value: items, child: Text(items));
  }).toList(),
  onChanged: (newValue) {
    setState(() {
      dropdownvalue = newValue;
    });
  },
),

You don't need to specify type on items or newValue parameters. Also no need to use async keyword on onChanged function if you won't do any async operation.

CodePudding user response:

DropdownButton is a generic provide it with T like so DropdownButton<String> and then you can remove Object? and have String? instead, but it'll be inferred anyways now so you probably don't need to specify the type here.

  • Related