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

Flutter下拉菜单联动显示实现及代码错误解决求助

问题分析与解决方案

你的代码存在几个关键错误,导致运行异常,以下是问题点和修正方案:

错误点梳理

  1. Visibility显示逻辑错误:当前只要selectedValue不为null就显示二级下拉,但需求是仅选中「KHS」时才显示
  2. 空值赋值错误:selectSmt = null!是强制将null转为非空类型,会触发空安全错误,直接赋值null即可
  3. 无效的列表过滤:listItem2.where((element) => element?.contains(selectedValue))完全错误,int类型没有contains方法,且我们不需要过滤学期列表
  4. 类型转换错误:Text(value as String)试图将int强制转为String,会抛出类型转换异常,应该用toString()方法转换

修正后的完整代码

初始化代码(补充变量定义)

String? selectedValue;
int? selectSmt;
List<String> listItem = [
  'Transkrip Sementara',
  'KHS',
];
List<int> listItem2 = [1,2,3,4,5,6,7,8];

Widget代码

const SizedBox(height: 8),
Container(
  width: double.infinity,
  height: 50,
  decoration: BoxDecoration(
    color: Colors.white,
    borderRadius: BorderRadius.circular(8),
    border: Border.all(color: Colors.grey),
  ),
  child: Padding(
    padding: const EdgeInsets.all(8.0),
    child: DropdownButtonHideUnderline(
      child: DropdownButton<String>(
        hint: const Text('Pilih Jenis Transkrip'),
        value: selectedValue,
        onChanged: (newValue) {
          setState(() {
            selectedValue = newValue;
            selectSmt = null; // 修正空值赋值,取消强制非空
          });
        },
        items: listItem.map((valueItem) {
          return DropdownMenuItem<String>(
            value: valueItem,
            child: Text(valueItem),
          );
        }).toList(),
      ),
    ),
  ),
),
// 修正显示条件:仅选中KHS时显示二级下拉
Visibility(
  visible: selectedValue == 'KHS',
  child: DropdownButton<int>(
    value: selectSmt,
    hint: const Text('Pilih Semester'), // 可选:添加提示文本
    // 移除无效的where过滤,直接映射列表
    items: listItem2.map((value) {
      return DropdownMenuItem<int>(
        value: value,
        child: Text(value.toString()), // 用toString()转换int为String
      );
    }).toList(),
    onChanged: (value) {
      setState(() {
        selectSmt = value;
      });
    },
  ),
),

关键修改说明

  • 调整Visibility的visible参数为selectedValue == 'KHS',精准控制二级下拉的显示时机
  • 将selectSmt = null!改为selectSmt = null,符合Dart空安全规范
  • 删除无效的where过滤逻辑,因为学期列表不需要根据选中值过滤
  • 把Text(value as String)替换为Text(value.toString()),正确将int转为字符串显示

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.26 00:47:35