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
}
)
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
}
}
)
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?)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With