FutureBuilder(
future: GetLiter(),
builder: (context, snapshot) => Text(
"Estimated bill \n\n\n" snapshot.data * 0.00556 " $",
textAlign: TextAlign.center,
style: TextStyle(fontSize: 20),
), // Text
), // FutureBuilder
I have "An expression whose value can be 'null' must be null-checked before it can be dereferenced." error in snapshot.data. How can I null-check this?
GetLiter() func is here =>
Future<Object?> GetLiter() async {
FirebaseDatabase database = FirebaseDatabase.instance;
DatabaseReference ref = FirebaseDatabase.instance.ref("Liter");
DatabaseEvent event = await ref.once();
// print(event.snapshot.value);
return event.snapshot.value;
}
CodePudding user response:
FutureBuilders do not wait for the future to complete before they build and therefore snapshot.data
could be null. You need to check this before you build or else the build will fail. Try this out:
import 'package:flutter/material.dart';
FutureBuilder(
future: GetLiter(),
builder: (context, snapshot) {
if(snapshot.hasError){
print(snapshot.error);
}
if(snapshot.hasData){
return Text(
"Estimated bill \n\n\n" snapshot.data! * 0.00556 " $",
textAlign: TextAlign.center,
style: TextStyle(fontSize: 20),
),
} else {
return CircularProgressIndicator();
}
}
),
CodePudding user response:
You can use snapshot.hasData
on your builder
to check if it is null. For example:
FutureBuilder(
future: GetLiter(),
builder: (context, snapshot) {
if (!snapshot.hasData) return Text('Nothing here');
return Text(
"Estimated bill \n\n\n" snapshot.data * 0.00556 " $",
textAlign: TextAlign.center,
style: TextStyle(fontSize: 20),
)
}, // Text
),
CodePudding user response:
While using FutureBuilder
you need to await for data and handle loading state and null data.
child: FutureBuilder<Object?>(
future: GetLiter(),
builder: (context, snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
} else if (snapshot.hasData &&
snapshot.connectionState == ConnectionState.done) {
return Text("Got Data");
} else if (!snapshot.hasData) {
return Text("no Data");
} else if (snapshot.hasError) {
return Text(snapshot.error.toString());
} else {
return Text("others");
}
},
),
More about FutureBuilder