首页 > 解决方案 > type '(dynamic) => Null' 不是 '(String, dynamic) => void' of 'f' 的子类型

问题描述

我正在尝试填充从 Web API 检索到的数据:

  void asyncInitState() async {
    BulletinController bulletinController = BulletinController() ;
    var value = await bulletinController.AfficherEtablissement();
    value.forEach((entry) {
      print(entry['id']);
    });
  }

  @override
  void initState() {
    super.initState();
    asyncInitState(); 
    super.initState();
  }

这是“AfficherEtablissement()”方法:

 Future<dynamic> AfficherEtablissement() async {
     final response =
     await http.get('https://jsonplaceholder.typicode.com/albums/1');
     if (response.statusCode == 200) {
       var parsedJson = json.decode(response.body);
       //decode
       print(parsedJson);
       Map<String, dynamic> data = json.decode(response.body);
       return data  ;
     } else {
       throw Exception('Failed to load');
     }
   }

我收到此错误:

type '(dynamic) => Null' is not a subtype of type '(String, dynamic) => void' of 'f'

在他的行中:

print(entry['id']);

标签: flutter

解决方案


AfficherEtablissement函数返回一个Map对象,因此对于响应迭代,您应该使用:

value.forEach((key, value) {
   // do something
});

请注意,您传递给 forEach 的函数有两个参数(键、值)。


推荐阅读