列表为空时Flutter下拉菜单项错误



我尝试从API JSON填充下拉菜单项。我的代码中有myList。有时,此列表为空,有时列表包含数据。

如果myList有数据,则没有问题。myList为空时我遇到问题。我该如何解决这个问题?

我的型号类别:

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"],
callListDto: List<CallListDto>.from(
json["callListDto"].map((x) => CallListDto.fromJson(x))),
);
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"],
stationCode: json["stationCode"],
callType: json["callType"],
);
Map<String, dynamic> toJson() => {
"callID": callId,
"stationCode": stationCode,
"callType": callType,
};
}

我的下拉UI:

items: _loginController.loginList[0].myList
.where((p0) => p0.callType == 1)
.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如果列表中没有可用的项目,您将无法再访问下拉按钮,默认情况下,它将被禁用

class _MyHomePageState extends State<MyHomePage> {
String? val; //default value

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: DropdownButton(
onChanged: (value){},
value: val, // this is where you need to access it
items: [].map((e) {
return DropdownMenuItem(
value: e,
child: Text(e),
)
;
}).toList(),

)));
}
}

我解决了我的问题,如果它以前为null的话。

callListDto: json["callListDto"] != null
? List<CallListDto>.from(
json["callListDto"].map((x) => CallListDto.fromJson(x)))
: <CallListDto>[]

最新更新