在 flutter 中从 API 中获取数据时出现错误类型'_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable<dynamic>'

Getting error type'_InternalLinkedHashMap<String, dynamic>' is not a subtype of type 'Iterable<dynamic>' while fetching data from API in flutter

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

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

我正在从 API 获取新闻数据。我为简单的 API 尝试了这个并且它起作用了,当我为复杂的 API 尝试它并在飞镖代码中进行了一些更改时,我得到了这个错误。

抱歉,如果我没有正确解释。我已经粘贴了用于此 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'],
         );
       }

   }

技术_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

抱歉,如果我在这里粘贴了太多代码。

为什么会出现此错误,我该如何解决。

提前致谢。

您应该检查正确的响应类型 Int 和 String。我看到你的 API 状态:"ok" 确保你检查正确。

根据您的 json,没有列表,只有 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更改为

    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(),
              );
            }

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