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

Flutter中DropdownButton2删除选中项后应用崩溃问题求助

Flutter dropdown_button2 1.9.0:删除选中项后添加新Hive数据引发应用崩溃

问题详情

我已尝试谷歌搜索相关问题但未找到有效解决方案,因此发起提问。我基于Flutter框架开发,引入了dropdown_button2: ^1.9.0库,当前遇到的问题是:当删除CustomDropdownButton2的选中项后,再向Hive数据库中添加新项时,应用会直接崩溃。

经排查,确定崩溃根源是选中项被删除后,selectedValue变为null,进而触发报错。我尝试给selectedValue设置默认值,但并未解决问题。

相关代码

下拉按钮实现代码

CustomDropdownButton2(
  value: selectedValue,
  items: _hiveItemList.map((item) {
    return DropdownMenuItem<String>(
      value: item.id,
      child: Text(item.displayName),
    );
  }).toList(),
  onChanged: (value) {
    setState(() {
      selectedValue = value;
    });
  },
  // 其他配置参数
)

Hive数据操作代码

// 删除选中项方法
Future<void> deleteSelectedItem() async {
  final itemBox = await Hive.openBox('item_box');
  await itemBox.delete(selectedValue);
  setState(() {
    _hiveItemList = itemBox.values.toList();
    // 此处未处理已删除的selectedValue
  });
}

// 添加新项方法
Future<void> addNewItem(Item newItem) async {
  final itemBox = await Hive.openBox('item_box');
  await itemBox.put(newItem.id, newItem);
  setState(() {
    _hiveItemList = itemBox.values.toList();
  });
}

错误信息示例

Null check operator used on a null value
#0      DropdownButton2State.build (package:dropdown_button2/src/dropdown_button2.dart:352:5)
#1      StatefulElement.build (package:flutter/src/widgets/framework.dart:4919:27)
#2      ComponentElement.performRebuild (package:flutter/src/widgets/framework.dart:4802:15)
...

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.12 18:44:55