You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Flutter的Row组件中使用DropdownButton及报错解决

解决Flutter DropdownButton的断言错误问题

我帮你看了下你的代码和抛出的错误日志,问题其实很直观:你给DropdownButton设置的选中值不在选项列表里。

错误原因分析

看错误里的核心断言信息:

'items == null || items.isEmpty || value == null || items.where((DropdownMenuItem item) => item.value == value).length == 1': is not true.

这条规则的意思是:DropdownButton的value必须满足要么是null,要么在items列表里能找到恰好一个完全匹配的选项。而你的代码里:

  • _currencies列表的第一个元素是"Rupees"(带末尾的s)
  • 但你给DropdownButton设置的value: 'Rupee'(不带s)

两者完全不匹配,所以触发了断言错误。

修复方案

方案一:直接修正value值

把DropdownButton的value改成和列表里一致的"Rupees",同时建议加上onChanged回调(否则下拉菜单点击后无交互反应):

Expanded(child:DropdownButton<String>(
  items:_currencies.map((String value){
    return DropdownMenuItem<String>(
      value: value,
      child: Text(value),
    );
  }).toList(),
  value : 'Rupees', // 修正为带s的Rupees
  onChanged: (newValue) {
    setState(() {
      // 后续可以在这里更新选中状态
    });
  },
)),

方案二:用变量管理选中值(更推荐)

为了避免硬编码出错,建议在State类里定义一个变量跟踪选中状态,初始化时默认选中列表第一个选项:

class _SIFormState extends State<SIForm>{
  var _currencies = ["Rupees","USD","CAD"];
  String? _selectedCurrency; // 新增选中状态变量

  @override
  void initState() {
    super.initState();
    _selectedCurrency = _currencies[0]; // 初始选中第一个选项
  }

  @override
  Widget build(BuildContext context) {
    // ... 其他代码不变
    Row(
      children: <Widget>[
        Expanded(child:TextField(
          keyboardType: TextInputType.number,
          decoration: InputDecoration(
            labelText: 'Terms', hintText: '%'
          ),
        )),
        Expanded(child:DropdownButton<String>(
          items:_currencies.map((String value){
            return DropdownMenuItem<String>(
              value: value,
              child: Text(value),
            );
          }).toList(),
          value : _selectedCurrency, // 使用变量作为选中值
          onChanged: (newValue) {
            setState(() {
              _selectedCurrency = newValue; // 更新选中状态
            });
          },
        )),
      ],
    )
    // ... 其他代码不变
  }
}

额外提示

DropdownButton必须配合onChanged和setState使用,否则下拉菜单的选中状态无法同步到UI上,这是新手容易忽略的点。

内容的提问来源于stack exchange,提问作者pradeep murugan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.12 05:37:50