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

Flutter DropdownButton类型赋值错误:Object?无法分配给String?

解决DropdownButton类型不匹配错误:Object? 无法赋值给 String?

问题场景

我正在制作一个从MySQL数据库加载选项的DropdownButton,遇到如下类型不匹配错误:

A value of type 'Object?' can't be assigned to a variable of type 'String?'

原代码

String? selectedCategory;
List categoryItem=[];
....
DropdownButton(
    value: selectedCategory,
    hint: Text('Select category'),
    items: categoryItem.map((category) {
      return DropdownMenuItem(
        value: category['name'],
          child: Text(category['name']));
    }).toList(),
    onChanged: ( value){
      setState(() {
        selectedCategory=value;
      });
    },
    isExpanded: true,
),

报错核心代码段

onChanged: ( value){
  setState(() {
    selectedCategory=value;
  });
}

尝试过但无效的写法

onChanged: (String? newValue) {
  setState(() {
    selectedCategory = newValue!;
  });
}

解决方案

问题根源是DropdownButton未指定泛型类型,导致框架默认将value推断为Object?,与你定义的String? selectedCategory类型不兼容。

方案1:为DropdownButton指定泛型<String?>

DropdownButton<String?>( // 明确指定泛型类型
    value: selectedCategory,
    hint: Text('Select category'),
    items: categoryItem.map((category) {
      return DropdownMenuItem<String?>( // 同步为子项指定泛型
        value: category['name'],
        child: Text(category['name']));
    }).toList(),
    onChanged: (String? newValue) {
      setState(() {
        selectedCategory = newValue;
      });
    },
    isExpanded: true,
),

方案2:对value进行显式类型转换

如果不想指定泛型,可在赋值时强制转换类型:

onChanged: (value){
  setState(() {
    selectedCategory = value as String?;
  });
}

额外优化建议

建议给categoryItem也指定具体类型,避免后续潜在的类型问题:

List<Map<String, dynamic>> categoryItem = [];

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.25 05:40:11