【问题标题】:Flutter - The argument type 'Iterable>' can't be assigned to type 'List'Flutter - 参数类型“Iterable>”不能分配给类型“List”
【发布时间】:2021-06-26 03:35:04
【问题描述】:

我想在每个 api 调用中再获取 5 条记录并将它们添加到现有列表中。 但是,下面的结构给出了错误。错误截图和完整的代码结构如下。

探索页面初始化

 @override
  void initState() {
        exploreController.fetchArticles(offsetCount: page);
    super.initState();
    _sc.addListener(() {
      if (_sc.position.pixels == _sc.position.maxScrollExtent) {
        page = page + 5;
        exploreController.fetchArticles(offsetCount: page);
      }
    });
  }

探索模型

List<ExploreModel> exploreModelFromJson(String str) => List<ExploreModel>.from(
    json.decode(str).map((x) => ExploreModel.fromJson(x)));

String exploreModelToJson(List<ExploreModel> data) =>
    json.encode(List<dynamic>.from(data.map((x) => x.toJson())));

我的 api 调用

static Future<List<ExploreModel>> fetchArticleList(int offsetCount) async {
    var url = Uri.http(Config().baseUrl, Config().baseUrlPathGetArticles,
        {'offsetCount': '$offsetCount'});
    var response = await http.get(url);
    if (response.statusCode == 200) {
      return exploreModelFromJson(utf8.decode(response.bodyBytes));
    } else {
      return null;
    }
  }

和我的控制器

class ExploreController extends GetxController {
  var isLoading = true.obs;
  var articleList = <ExploreModel>[].obs;
  var offsetCount = 0;

  @override
  void onInit() {
    fetchArticles();
    super.onInit();
  }

  void fetchArticles({int offsetCount = 0}) async {
    try {
      isLoading(true);
      var articles = await ApiService.fetchArticleList(offsetCount);

      if (articles != null) {
        for (int i = 0; i < articles.length; i++) {
          articleList.addAll(articles[i]);
        }
      }
    } finally {
      isLoading(false);
    }
  }
}

This is what i want to make

【问题讨论】:

  • 当您使用“articles[i]”时,您只是将列表中的一个项目作为参数传递。 .addAll() 方法需要整个 List 作为参数,它只会从参数 List 中获取每个项目并将其添加到调用 .addAll() 的列表中。所以我猜你真的只想做“articleList.addAll(articles);” (当然,在这种情况下也不需要“for”循环)您的问题标题与您收到的实际错误不正确
  • 我下面的回答没有解决这个问题并帮助您前进吗?

标签: list flutter scroll flutter-getx


【解决方案1】:

改变这个:

List<ExploreModel> exploreModelFromJson(String str) => List<ExploreModel>.from(
    json.decode(str).map((x) => ExploreModel.fromJson(x)));

到这里:

List<ExploreModel> exploreModelFromJson(String str) => List<ExploreModel>.from(
    json.decode(str).map((x) => ExploreModel.fromJson(x)).toList()); //add the toList().

【讨论】:

  • 我的朋友感谢您的回答。这解决了我的列表类型问题。
  • 它解决了这个问题的问题,不客气。
猜你喜欢
  • 2020-05-28
  • 2021-11-13
  • 2021-12-24
  • 2021-07-25
  • 2019-10-05
  • 2021-07-10
  • 2021-05-25
  • 2021-07-05
  • 2021-11-23
相关资源
最近更新 更多