[英]Flutter Dropdown with API call
error:错误:
Exception: type 'List<dynamic>' is not a subtype of type 'List<DropdownMenuItem<int>>?'
Dropdown:落下:
FutureBuilder(
future: customerServices.fetchApiFromUrl(),
builder:
(BuildContext context, AsyncSnapshot snapshot) {
if (!snapshot.hasData) {
return const Center(
child: CircularProgressIndicator());
} else {
try {
final snapshotData = snapshot.data;
return DropdownButton(
borderRadius: BorderRadius.circular(15),
value: dropdownValue,
icon: const Icon(
Icons.arrow_downward,
color: Colors.white,
),
elevation: 16,
style: const TextStyle(color: Colors.black),
underline: Container(
height: 2,
color: Colors.white,
),
onChanged: (int? newValue) {},
items: snapshotData.map((Customer customer) {
return DropdownMenuItem(child: Text(customer.first_name!), value: customer.id);
}).toList()
);
} catch (e) {
throw Exception(e);
}
}
},
), ),
API Call API 拨打
Future fetchApiFromUrl() async {
final SharedPreferences sharedPreferences =
await SharedPreferences.getInstance();
List<Customer> data = CustomerListResponse.fromJson(jsonDecode(response.body)).results!;
if (response.statusCode == 200) {
if (kDebugMode) {
log("res ${(data)}");
}
return data;
}
}
It seems related to the type it infers from your snapshot.map().toList()
.它似乎与它从您的snapshot.map().toList()
推断出的类型有关。
Try giving explicit type to it as snapshot.map<DropdownMenuItem<int>>().toList()
, see the below code for this:尝试将其显式指定为snapshot.map<DropdownMenuItem<int>>().toList()
,请参阅以下代码:
return DropdownButton(
...
onChanged: (int? newValue) {},
items: snapshotData.map<DropdownMenuItem<int>>((Customer customer) {
return DropdownMenuItem(child: Text(customer.first_name!), value: customer.id);
}).toList()
);
You can also try changing the onChanged() to dynamic by not typecasting the parameter as:您还可以尝试通过不将参数类型转换为以下方式将 onChanged() 更改为动态:
onChanged: (newValue) {},
As the type of onChanged()
is void Function(dynamic), see the below image:由于onChanged()
的类型是void Function(dynamic),见下图:
Sure, it does work by typecasting it but you can try this as well as the version I use, I can't.当然,它确实可以通过类型转换来工作,但你可以尝试这个以及我使用的版本,我不能。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.