【问题标题】:Unhandled Exception: type 'int' is not a subtype of type 'String' on DropdownButton未处理的异常:类型“int”不是 DropdownButton 上“String”类型的子类型
【发布时间】:2021-06-26 12:26:29
【问题描述】:

我正在从 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,
),

我的代码有什么问题吗?请帮忙?

【问题讨论】:

  • item 对象是什么?
  • 项目为List

标签: flutter dart dropdown


【解决方案1】:

我的代码有什么问题吗?

类型不匹配。

类型变量_provinceSelected 被定义为String 类型,但是当将值分配给int 类型时,由于item['id']int

更新DropdownButton 以设置Type 值,如DropdownButton<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,
),

【讨论】:

  • 我已尝试将变量转换为 int _provinceSelected,但仍然无法正常工作。
  • 出现另一个错误:link
  • 非唯一值被赋予DropdownButton,似乎值16重复了
  • 你是对的,我在数据库中有多个具有相同 ID 的数据。 link
  • ID 列应始终在 SQL 数据库中使用 Unique :)
【解决方案2】:

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

【讨论】:

  • 这发生在我将 _provinceSelected 更改为 int 时。 link
猜你喜欢
  • 2021-09-19
  • 1970-01-01
  • 2021-07-08
  • 2020-04-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多