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

Flutter的BottomSheet中添加多个下拉菜单出现报错该如何解决?

问题解答

首先明确:Flutter 的 BottomSheet 完全支持创建多个下拉菜单,你的报错和 BottomSheet 本身的能力无关,是代码编写失误导致的,具体问题和修复方案如下:

错误1:flavour 列表存在语法错误

你的 flavour 数组中,'Kiwi' 项末尾漏掉了逗号,导致后续的 'Select' 字符串和 'Kiwi' 直接拼接为了单个值 'KiwiSelect',列表元素不符合预期。同时你把'Select'放在了列表末尾,和杯型列表的默认值逻辑不统一。
修复后的列表代码:

final List<String> cupsize = ['Select', 'Small', 'Medium', 'Large'];

final List<String> flavour = [
  'Select',
  'Chocolate',
  'Vanilla',
  'Strawberry',
  'Blueberry',
  'Raspberry',
  'Kiwi'
];

String? _currentCupSize;
String? _currentFlavour;

错误2:口味下拉的默认值不存在

Dropdown 控件要求传入的 value 必须是 items 列表中存在的某个值,你给口味下拉设置的 fallback 值是 'One',但这个值在 flavour 列表中完全不存在,这是触发报错的直接原因。
修复后的下拉代码:

// 杯型下拉(原有逻辑无需修改,可正常运行)
DropdownButtonFormField(
  value: _currentCupSize ?? 'Select',
  items: cupsize.map((size) {
    return DropdownMenuItem(
      value: size,
      child: Text('$size Size'),
    );
  }).toList(),
  onChanged: (val) => setState(() {
    _currentCupSize = val as String?;
  }),
),

// 修复后的口味下拉
DropdownButtonFormField(
  value: _currentFlavour ?? 'Select',
  items: flavour.map((flav) {
    return DropdownMenuItem(
      value: flav,
      child: Text('$flav Flavour'),
    );
  }).toList(),
  onChanged: (val) => setState(() {
    _currentFlavour = val as String?;
  }),
),

补充说明

如果你的项目开启了空安全,建议给 DropdownButtonFormField 明确泛型类型,比如 DropdownButtonFormField<String>,可以避免类型转换的潜在警告。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.21 03:36:03