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

Flutter中DropdownButton组件无法正常工作的原因排查

Flutter DropdownButton报错修复

错误原因

  • 拼写失误:selectedItem初始值写为'samll',但可选列表items中对应的正确值是'small',拼写错误导致DropdownButton无法匹配到合法选中值,触发报错。
  • 未显式指定DropdownButton的泛型类型,可能引发类型推断异常,建议明确声明类型。

修正后的代码

class MyPage extends StatefulWidget {
  MyPage({super.key});

  @override
  State<MyPage> createState() => _Example();
}

class _Example extends State<MyPage> {
  List<String> items = ['small', 'medium', 'large', 'extra-large'];
  String? selectedItem = 'small'; // 修正拼写错误

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          title: const Text('HDBOOKS'),
        ),
        body: DropdownButton<String>( // 显式指定泛型类型
          value: selectedItem,
          items: items
              .map((e) => DropdownMenuItem(value: e, child: Text(e)))
              .toList(),
          onChanged: (item) => setState(() {
            selectedItem = item!;
          }),
        ));
  }
}

补充说明

DropdownButton要求value必须是items列表中存在的可选值,否则会抛出错误,这是Flutter保障下拉框选中值合法性的机制。显式声明泛型类型能让代码逻辑更清晰,避免潜在的类型相关问题。

内容的提问来源于stack exchange,提问作者Hana.HD

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.06 13:32:09