首页 > 解决方案 > 如何在 http 调用中修复奇怪的飞镖错误

问题描述

我在运行时收到以下错误,我正在执行 http 调用并返回 json。

“_TypeError(类型'List'不是类型'() => void'的子类型)”

这是我的代码

   class _ForumPostsState extends State<ForumPosts> {
List data;
String categoryID = 'D64D0737-746D-4562-8C10-6445F4069A92';
Future<String> getPostsByCategory() async {
    var response = await http.post(
 Uri.encodeFull("http://api/ForumPostsByCategory"),
      headers: {"Content-Type": "application/json", 
             'Accept': 'application/json',},
      body: json.encode({'categoryID' : categoryID }));  
     this.setState(
         data = json.decode(response.body)

     );
    print(data[1]["title"]);

return "Success!";
}

此行抛出错误

data = json.decode(response.body)

在调试时,我注意到 JSON 在那里,它只是 data = json.decode 调用上的错误。

标签: dartflutter

解决方案


改变这个:

this.setState(
     data = json.decode(response.body)

  );

对此:

 this.setState(() {
     data = json.decode(response.body)
    }
 );

更多信息:https ://docs.flutter.io/flutter/widgets/State/setState.html


推荐阅读