未处理的异常:类型 'int' 不是 DropdownButton 类型 'String' 的子类型

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

我正在从 API 创建 DropdownButton。下拉列表已经按照我的需要显示了,但问题是我选择的列表没有显示,点击列表时出现错误:

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

这是我的变量声明:

String _provinceSelected;

这是我的 DropdownButton 小部件:

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?

类型不匹配。

类型变量 _provinceSelected 被定义为 String 类型,但是当值被赋值时它被赋值给 int 类型,因为 item['id']作为 int.

更新 DropdownButton 以设置这样的 TypeDropdownButton<String> 并将值定义更新为 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,
),

我认为您对 id (int)_provinceSelected (String) 的数据类型有疑问。因为 DropdownMenuItem 中 id 的值将 onChanged 函数中的 return 值。所以你可以改变id to String_provinceSelected to int的数据类型。希望对你有帮助。