A value of type 'Object?' can't be assigned to a variable of type 'String'

190 views Asked by At
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;
                  }
                  );
                },
              ),
3

There are 3 answers

0
moneer alhashim On

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.

0
tomerpacific On

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;
                  }
                  );
                },
              ),
0
A. Sahin On

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.