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

Flutter下拉菜单列表为空时出错的解决方法咨询

解决Flutter下拉菜单列表为空时的异常问题

一、修复模型类的空值兼容

当前Login.fromJson构造函数在API返回callListDto为null或空数组时会直接抛出异常,需增加空值判断兜底:

Login loginFromJson(String str) => Login.fromJson(json.decode(str));

String loginToJson(Login data) => json.encode(data.toJson());

class Login {
  Login({
    required this.token,
    required this.callListDto,
  });

  String token;
  List<CallListDto> callListDto;

  factory Login.fromJson(Map<String, dynamic> json) => Login(
        token: json["token"] ?? "", // 给token加空值兜底
        callListDto: (json["callListDto"] as List?)?.map((x) => CallListDto.fromJson(x)).toList() ?? [],
      );

  Map<String, dynamic> toJson() => {
        "token": token,
        "callListDto": List<dynamic>.from(callListDto.map((x) => x.toJson())),
      };
}

class CallListDto {
  CallListDto({
    required this.callId,
    required this.stationCode,
    required this.callType,
  });

  int callId;
  String stationCode;
  int callType;

  factory CallListDto.fromJson(Map<String, dynamic> json) => CallListDto(
        callId: json["callID"] ?? 0, // 字段空值兜底
        stationCode: json["stationCode"] ?? "",
        callType: json["callType"] ?? 0,
      );

  Map<String, dynamic> toJson() => {
        "callID": callId,
        "stationCode": stationCode,
        "callType": callType,
      };
}

二、修复下拉菜单的空列表处理

直接调用空列表的where/map方法会触发异常,需先判断列表存在性,为空时提供默认提示项:

// 先获取过滤后的有效列表
final filteredList = (_loginController.loginList.isNotEmpty 
        ? _loginController.loginList[0].myList ?? [] 
        : [])
    .where((p0) => p0.callType == 1)
    .toList();

// 构建下拉菜单items
items: filteredList.isEmpty
    ? [
        DropdownMenuItem<String>(
          value: "",
          child: Text(
            "暂无数据",
            style: GoogleFonts.ptSansNarrow(
              textStyle: TextStyle(
                  fontSize: 25,
                  fontWeight: FontWeight.w600,
                  color: Colors.grey.withOpacity(.8)),
            ),
          ),
        )
      ]
    : filteredList.map(
        (item) => DropdownMenuItem<String>(
          value: item.callId.toString(),
          child: Text(
            item.callId.toString(),
            style: GoogleFonts.ptSansNarrow(
              textStyle: TextStyle(
                  fontSize: 25,
                  fontWeight: FontWeight.w600,
                  color: Colors.black.withOpacity(.8)),
            ),
          ),
        ),
      ).toList(),

关键注意点

  • 空值兜底:对模型字段、控制器列表都做null判断,避免空指针异常。
  • 默认选项:空列表时添加提示项,既提升用户体验,也避免下拉菜单因无items报错。
  • 数组越界防护:先判断loginList是否为空,再访问loginList[0],防止数组越界。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.14 15:55:20