本文介绍了收到此错误-输入"Future< dynamic>"不是类型"List< dynamic>"的子类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

每当尝试调用将来的数据并尝试转换为 List 时,都会返回错误

Whenever trying to call future data and trying converting to List, it returns the error

尝试类型转换,但无济于事

Tried type-casting, but no help

在HomePage.dart上

On HomePage.dart

final getPost = NetworkFile().getPosts();
  List posts;

  void getPostsList() {
    setState(() {
      var res = getPost;
      posts = res as List<dynamic>;
      print(posts);
    });
  }

在Network.dart上

On Network.dart

class NetworkFile{

Future<dynamic> getPosts() async {
    var response = await http.get('$kBlogURL' + 'posts?_embed');
    Iterable resBody = await jsonDecode(response.body.toString());
    return resBody;
  }
}

推荐答案

您正在解码响应及其类型为 dynamic List .处理它的方法很少.您可以创建一个简单的PODO类并对其进行强制转换/映射.或只是如下所示:

You are decoding the response and its a List of type dynamic. There are few method to handle it. You can create a simple PODO class and cast/mapped to it. Or just do like below:

List posts = [];

void getPostsList() async {
  final fetchedPosts = await NetworkFile().getPosts();
  setState(() {
    posts = fetchedPosts;
  });
  print(posts);
}

这是一篇有关PODO的不错的文章

这篇关于收到此错误-输入"Future&lt; dynamic&gt;"不是类型"List&lt; dynamic&gt;"的子类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 01:34