Search code examples
flutterdartdropdown

Unhandled Exception: type 'int' is not a subtype of type 'String' on DropdownButton


I'm creating DropdownButton from API. The dropdown list has been shown as I need, but the problem is the list I selected is not shown as well, and the error shows when I click the list:

Unhandled Exception: type 'int' is not a subtype of type 'String'

Here is my variable declaration:

String _provinceSelected;

Here is my DropdownButton Widget:

DropdownButton(
  hint: Text('your province'),
  itemHeight: 60,
  isExpanded: true,
  items: dataProvince.map((item) {
    return DropdownMenuItem(
      child: Text(item['name']),
      value: item['id'],
    );
  }).toList(),
  onChanged: (value) {
    setState(() {
      _provinceSelected = value;
    });
  },
  value: _provinceSelected,
),

Is there any thing wrong on my code? Please help?


Solution

  • Is there any thing wrong on my code?

    There is a type mismatch.

    The type variable _provinceSelected is defined to be of type String, however when the value is assigned it assigned to a type of int, due to item['id'] being an int.

    Update the DropdownButton to set a Type value like this DropdownButton<String> and update the value definition to be a String.

    
    DropdownButton<String>(
      hint: Text('your province'),
      itemHeight: 60,
      isExpanded: true,
      items: dataProvince.map((item) {
        return DropdownMenuItem(
          child: Text(item['name']),
          value: item['id'].toString(),
        );
      }).toList(),
      onChanged: (value) {
        setState(() {
          _provinceSelected = value;
        });
      },
      value: _provinceSelected,
    ),