Flutter Futurebuilder snapshot is null

496

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;
  }
}
Share:
496
Tutorialwork
Author by

Tutorialwork

App &amp; Webdeveloper 🎇 Javascript/Typescript &amp; 🎯 Dart Flutter, Angular, NodeJS... 🇩🇪 Germany

Updated on December 16, 2022

Comments

  • Tutorialwork
    Tutorialwork over 1 year

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

    }

    • pskink
      pskink over 4 years
      wait, you mean that AsyncSnapshot snapshot is null? or snapshot.data?
    • Tutorialwork
      Tutorialwork over 4 years
      I mean snapshot.data
    • pskink
      pskink over 4 years
      maybe because of: } else { return null; }?
    • Tutorialwork
      Tutorialwork over 4 years
      I have tried it and the same result
    • pskink
      pskink over 4 years
      so do you return non null value from _getBans() method? are you sure?
    • Tutorialwork
      Tutorialwork over 4 years
      Yes. Then I print the length before the return with print(bans.length); and I will get the current length.
    • Tutorialwork
      Tutorialwork over 4 years
      I see this two lines flutter: AsyncSnapshot<dynamic>(ConnectionState.waiting, null, null) and flutter: AsyncSnapshot<dynamic>(ConnectionState.done, null, null)
    • Tutorialwork
      Tutorialwork over 4 years
      Yes, I get hello world as snap.data. But how I can get my fetched data in the Futurebuilder?
  • Noor
    Noor almost 3 years
    Can you please help me resolve this? stackoverflow.com/questions/67813247/…