简体   繁体   中英

Flutter Futurebuilder snapshot is null

I try to show the results from JSON in a ListView in Flutter with a FutureBuilder. But the snapshot is null and the message that no data is available shows.

Here I try to fetch the data:

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

}

from this JSON response

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

My Futurebuilder. Here is snapshot null but the count of the elements is working.

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

}

Please try this. I think you'll have to use await keyword for the getLoggedToken mothod, the return will wait for the post before returning anything. But now you're returning before the getLoggedToken finishes his work. That is why you are always receiving 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;
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM