首页 > 解决方案 > 获取数据颤动列表

问题描述

我只想获取我的模型的整个列表并在我的回复中>

我无法将 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"],
      );
}

标签: flutterdart

解决方案


 try {
      final response = await ApiService().fetchData({
        ListView.builder(
                    itemCount:20           
      });

.try 列表视图生成器可能会起作用并尝试初始化

List<AstronomyModel>

.在您的屏幕上可能有效。谢谢


推荐阅读