Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

snapshot.data is null in flutter

Tags:

flutter

My snapshot.data is null. When I print the response it is displaying the retrieved data. But still snapshot.data is null.

    Future _getUsers() async {
         
        var data = await http.post("http://10.0.2.2/Flutter/abreport.php", body: {
        {
          "date": mydt,
         });
         var jsonData = json.decode(data.body); //edited
         print(jsonData); // the data is printing here

         return jsonData;
       }  
    
       }  

    FutureBuilder(
            future: _getUsers(),
            builder: (BuildContext context, AsyncSnapshot snapshot) {
                  debugPrint(snapshot.data);
              if (snapshot.data == null) {
                return Container(
                  child: Center(
                
                    child:Text("no data"),
                    )
                    );
              } else {
                 //some code
             }

              ) 
like image 411
raj Avatar asked Mar 04 '23 03:03

raj


2 Answers

You should use the format given in the documentation for FutureBuilder. You're not checking for the state of the future, so when the FutureBuilder is first built, it will display "no data". You haven't implemented your else branch, so by the time you have data, your build will probably not refresh anyway. Try this code instead:

FutureBuilder(
  future: _getUsers(),
  builder: (BuildContext context, AsyncSnapshot snapshot) {
    if (snapshot.connectionState == ConnectionState.done) {
      if (snapshot.data == null) {
        return Text('no data');
      } else {
        return Text('data present');
      }
    } else if (snapshot.connectionState == ConnectionState.error) {
      return Text('Error'); // error
    } else {
      return CircularProgressIndicator(); // loading
    }
  }
)
like image 111
David L. Avatar answered Mar 11 '23 23:03

David L.


with Flutter 2.2, this one returns an error

builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
  if (snapshot.hasData) {
    return Text(snapshot.data,);

Error: The argument type 'String?' can't be assigned to the parameter type 'String' because 'String?' is nullable and 'String' isn't.
return Text(snapshot.data,);

but this one dosen't

builder: (BuildContext context, AsyncSnapshot snapshot) {

When similar things happen, take the type "var" not "String" or other non-nullable type. (If it was not Flutter, the compilers will do?)

like image 39
KHana Avatar answered Mar 12 '23 00:03

KHana