收到此错误-类型'Future <dynamic>'不是类型'List <dynamic>'的子类型

时间:2019-09-04 15:05:42

标签: flutter

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

  

“ Future”类型不是“ List”类型的子类型

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

在HomePage.dart

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

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

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

2 个答案:

答案 0 :(得分:0)

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

答案 1 :(得分:0)

您正在解码响应及其类型为List的{​​{1}}。处理它的方法很少。您可以创建一个简单的PODO类并对其进行强制转换/映射。或者只是像下面这样:

dynamic

Here is a nice article about PODO