Getting this error - type 'Future<dynamic>' is not a subtype of type 'List<dynamic>'

微笑、不失礼 提交于 2021-01-29 07:42:52

问题


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

type 'Future' is not a subtype of type 'List'

Tried type-casting, but no help

On HomePage.dart

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

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

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;
  }
} 


回答1:


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

Here is a nice article about PODO.




回答2:


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

void getPostsList() async {
  var res = await getPost;
  setState(() {
    posts = res as Map<String, dynamic>;
    print(posts);
  });
}


class NetworkFile {
  Future<dynamic> getPosts() async {
    var response = await http.get('https://onetechstop.net/wp-json/wp/v2');
    var resBody = await jsonDecode(response.body.toString());
    return resBody;
  }
}


来源:https://stackoverflow.com/questions/57791206/getting-this-error-type-futuredynamic-is-not-a-subtype-of-type-listdynam

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!