Flutter Futurebuilder快照为空

时间:2019-12-19 11:30:31

标签: json listview flutter dart future

我尝试使用FutureBuilder在Flutter的ListView中显示JSON的结果。 但是快照为空,并且显示没有可用数据的消息。

我在这里尝试获取数据:

static Future _getBans() async {
Storage.getLoggedToken().then((token) async {
  var body = {
    "token": token
  };
  final response = await http.post('${URLS.BASE_URL}/punishments.php', headers: ApiService.header, body: json.encode(body));
  if (response.statusCode == 200) {

    List<Ban> bans = [];
    var jsonData = json.decode(response.body)["bans"];
    for(var b in jsonData){
      Ban ban = Ban(b["player"], b["reason"], int.parse(b["end"]), b["by"]);
      bans.add(ban);
    }

    print(response.body);
    print(bans.length);

    return bans;
  } else {
    return null;
  }
});

}

从此JSON响应

{"status":1,"msg":"OK","bans":[{"player":"DDOSAttacke","reason":"Hacking","end":"1579275471304","by":"DDOSAttacke"}],"mutes":[]}

我的Futurebuilder。这是快照null,但元素计数正常。

Widget build(BuildContext context) {
return Scaffold(
  appBar: AppBar(
    title: Text('Aktive Bans'),
  ),
  body: Container(
    child: FutureBuilder(
      future: _getBans(),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        if (snapshot.data == null) {
          return Container(
            child: Center(
                child: Text('Keine aktiven Ban vorhanden')
            ),
          );
        } else {
          return ListView.builder(
            itemCount: snapshot.data.length,
            itemBuilder: (BuildContext context, int index) {
              return ListTile(
                title: Text(snapshot.data[index].player),
              );
            },
          );
        }
      },
    ),
  ),
);

}

1 个答案:

答案 0 :(得分:0)

请尝试这个。我认为您必须为await方法使用getLoggedToken关键字,return将等待帖子返回任何内容。但是现在您要在getLoggedToken完成工作之前返回。这就是为什么您总是收到null的原因。

 static Future _getBans() async {
 var token = await Storage.getLoggedToken();
      var body = {
        "token": token
      };
      final response = await http.post('${URLS.BASE_URL}/punishments.php', headers: ApiService.header, body: json.encode(body));
      if (response.statusCode == 200) {

    List<Ban> bans = [];
    var jsonData = json.decode(response.body)["bans"];
    for(var b in jsonData){
      Ban ban = Ban(b["player"], b["reason"], int.parse(b["end"]), b["by"]);
      bans.add(ban);
    }

    print(response.body);
    print(bans.length);

    return bans;
  } else {
    return null;
  }
}