Issue
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;
}
Solution
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();
}
}
),
Answered By – Zach
Answer Checked By – Cary Denson (FlutterFixes Admin)