【问题标题】:Getting error type'_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable<dynamic>' while fetching data from API in flutter在flutter中从API获取数据时获取错误类型'_InternalLinkedHashMap<String,dynamic>'不是'Iterable<dynamic>'类型的子类型
【发布时间】:2021-04-22 17:05:36
【问题描述】:

我是 Flutter 新手,我尝试从 API 获取数据,但出现错误

type'_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable<dynamic>'.

我正在从 API 获取新闻数据。我对简单的 API 进行了尝试,但它确实有效,当我对复杂的 API 进行尝试时,对 dart 代码进行了一些更改,我得到了这个错误。

对不起,如果我没有正确解释。我已经粘贴了用于此 API 的所有代码。

我没有得到任何解决方案。我在这里发布我的代码。

post.dart

 class Post {
     List<Articles> articles;

     Post({this.articles});

     factory Post.fromJson(Map<String, dynamic> json) {
        return Post(
           articles: json['articles'].map((value) => new Articles.fromJson(value)).toList(),
     );
  }
}

article.dart

 class Articles{
     final String title;
     final String description;
     final String url;
     final String urlToImage;
     final String publishedAt;
     final String content;

      Articles({this.title, this.description, this.url, this.urlToImage, this.publishedAt, this.content});

      factory Articles.fromJson(Map<String, dynamic> json) {
          return Articles(
              title: json['title'],
              description: json['description'],
              url: json['url'],
              urlToImage: json['urlToImage'],
              publishedAt: json['publishedAt'],
              content: json['content'],
         );
       }

   }

technology_post.dart

   Future<List<Post>> fetchPost() async {
      final response = await http.get('https://newsapi.org/v2/top-headlines?sources=techcrunch&apiKey=47ada2986be0434699996aaf4902169b');
      if (response.statusCode == 200) {
          var responseData = json.decode(response.body);
          List<Post> posts = [];
          for(var item in responseData){
             Post news = Post.fromJson(item);
             posts.add(news);
          }
       return posts;
      } else {
           throw Exception('Failed to load post');
      }
  }

  class Technology extends StatelessWidget{
      final Future<List<Post>> post;
      Technology({Key key, this.post}) : super (key : key);

      @override
      Widget build(BuildContext context) {
        return Scaffold(
          body: Center(
            child: FutureBuilder<List<Post>>(
               future: post,
               builder: (context, snapshot) {
                  if (snapshot.hasData) {
                      return ListView.builder(
                         itemBuilder: (BuildContext context, int index){
                         var dataStored = "";
                         for(var i = 0; i < 10; i++){
                             dataStored = snapshot.data.articles[i].title;
                             return ListTile(
                                title: Text(dataStored),
                             );
                         }
                     }
                );
        } else if (snapshot.hasError) {
          return Text("${snapshot.error}");
        }
         return CircularProgressIndicator();
        },
      ),
     ),
   );
  }
}

homescreen.dart

  TabBarView(
              children: [
                Technology(post: fetchPost()),
                Text('General'),
                Text('Cricket')
              ]

我已经发布了我希望的所有必需代码。如果你想看 API 你可以看到here

对不起,如果我在这里粘贴了很多代码。

为什么会出现此错误以及如何解决此问题。

提前致谢。

【问题讨论】:

    标签: json flutter dart fetch-api


    【解决方案1】:

    根据您的 json,没有 List 而只有 Post,因为 json 是 json 对象。 所以改变你的 fetchPost() 函数如下:

        Future<Post> fetchPost() async {
        final response = await http.get(
        'https://newsapi.org/v2/top-headlines? 
        sources=techcrunch&apiKey=$YOUR_API_KEY');
        if (response.statusCode == 200) {
        var responseData = jsonDecode(response.body);
        var post = Post.fromJson(responseData);
        return post;
        } else {
        throw Exception('Failed to load post');
        }
        }
    

    注意:从您的问题中删除您的 api 密钥并粘贴 json 仅出于隐私考虑。

    并将您的技术类更改为

        class Technology extends StatelessWidget {
                          final Future<Post> post;
    
                          Technology({Key key, this.post}) : super(key: key);
    
                          @override
                          Widget build(BuildContext context) {
                            return Scaffold(
                              body: Center(
                                child: FutureBuilder<Post>(
                                  future: post,
                                  builder: (context, snapshot) {
                                    if (snapshot.hasData) {
                                      return ListView.builder(
                                          itemBuilder: (BuildContext context, int index) {
                                        return Text(snapshot.data.articles[0].publishedAt);
                                      });
                                    } else if (snapshot.hasError) {
                                      return Text("${snapshot.error}");
                                    }
                                    return CircularProgressIndicator();
                                  },
                                ),
                              ),
                            );
                          }
                        }
    

    您的主要问题还在于您没有将 json['articles'] 转换为列表。您应该将 Post.fromJson 函数更改为

                        factory Post.fromJson(Map<String, dynamic> json) {
                  return Post(
                    articles: (json['articles'] as List).map((value) => new Articles.fromJson(value)).toList(),
                  );
                }
    

    这应该可以解决您的问题。

    【讨论】:

    • @sivaperumal 很高兴为您提供帮助。
    【解决方案2】:

    您应该使用字符串检查正确的响应类型 Int。我看到您的 API status: "ok" 并确保您检查正确。

    【讨论】:

    • 对不起,我是新手,我没有得到你。你能简单解释一下吗?
    • 您应该检查以解析来自 API 的响应。当我声明错误的类型 Int 和 String 时,我遇到了类似的错误。
    猜你喜欢
    • 2019-01-03
    • 2020-11-25
    • 2021-06-19
    • 1970-01-01
    • 2019-03-23
    • 2021-11-06
    • 2020-11-30
    • 2022-11-11
    • 2019-03-14
    相关资源
    最近更新 更多