Tutorialwork
Tutorialwork

Reputation: 73

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

}

Upvotes: 1

Views: 556

Answers (1)

Constantin N.
Constantin N.

Reputation: 2839

Please try this. I think you'll have to use await keyword for the getLoggedToken mothod, the returnwill wait for the post before returning anything. But now you're returning before the getLoggedTokenfinishes 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;
  }
}

Upvotes: 1

Related Questions