flutter - 获取数据颤动列表
问题描述
我只想获取我的模型的整个列表并在我的回复中>
我无法将 HTTP 请求的结果分配给列表。有人可以提供我的代码中缺少的内容吗?
正如计数参数所说,我想获取 20 个项目的整个列表,但我得到一个 response.body 并且无法将它分配给我期望的列表。如何将其转换为列表?
我的错误:无法将 Future 分配给 Future<List>
基本反应:
class ApiService {
String baseUrl = astronomyApiUrl;
Future<http.Response> fetchData(Map<String, String> urlParams) async {
http.Response response;
var combinedUrl = combineUrl(urlParams: urlParams);
final url = Uri.parse(combinedUrl);
try {
response = await http.get(url);
} on Exception catch (e) {
throw e;
}
return response;
}
String combineUrl({Map<String, String>? urlParams}) {
final buffer = StringBuffer();
urlParams!.forEach((name, value) {
buffer.write("$name=$value&");
});
return "$baseUrl/api/?${buffer.toString()}";
}
}
列表响应:
class AstronomyService {
Future<List<AstronomyModel>?> getAstronomy() async {
try {
final response = await ApiService().fetchData({
"thumbs": true.toString(),
"count": "20",
});
if (response.statusCode == 200) {
final result = astronomyModelFromJson(response.body);
return result; //Cannot assinge Future<AstronomyModel> to Future<List<AstronomyModel>>
} else {
return null;
}
} on SocketException catch (e) {
throw e;
} on HttpException catch (e) {
throw e;
} on FormatException catch (e) {
throw e;
}
}
}
模型:
AstronomyModel astronomyModelFromJson(String str) =>
AstronomyModel.fromJson(json.decode(str));
class AstronomyModel {
AstronomyPicModel({
this.date,
this.hdurl,
this.description,
this.mediaType,
this.thumbnailUrl,
this.title,
this.url,
});
DateTime? date;
String? hdurl;
String? description;
String? mediaType;
String? thumbnailUrl;
String? title;
String? url;
factory AstronomyModel.fromJson(Map<String, dynamic> json) =>
AstronomyModel(
date: DateTime.parse(json["date"]),
hdurl: json["hdurl"],
description: json["description"],
mediaType: json["media_type"],
thumbnailUrl: json["thumbnail_url"],
title: json["title"],
url: json["url"],
);
}
解决方案
try {
final response = await ApiService().fetchData({
ListView.builder(
itemCount:20
});
.try 列表视图生成器可能会起作用并尝试初始化
List<AstronomyModel>
.在您的屏幕上可能有效。谢谢
推荐阅读
- angular - 如何使用 Angular 从 twitter api 读取属性
- keras - 如何访问包含预训练模型的自定义模型的即时激活?
- python - 如何从python中的不同文件调用函数?
- google-apps-script - 在 Google 幻灯片上自动更新电子表格范围
- python - 在 Python 中运行完成后,无法让更大的代码循环
- python - 如何使用 altair 在 hconcat 图表中显示两个不同的图例
- c# - iTextSharp:复制最后一页再创建一页
- apache-spark - spark-submitting to YARN 时出现“未知队列:root.default”错误
- android - 当我添加 networkSecurityConfig 标记时,React-native android 没有构建
- python-3.x - 如何加速 s3 桶对象过滤器