I was trying to calculate the percentage by retrieving the required field values from the firestore using FutureBuilder, while doing so I'm facing this error. Can someone please let me know the reason of this error and where I'm going doing wrong in the code. Please help me in solving this issue.
Here is the code :
displayPercentage() :
dynamic percentage = 0.0;
displayPercentage() async {
var totalClassesTook;
var totalClassesAttended;
try {
totalClassesTook =
await tutor_details.doc(uid).snapshots().map((event) async {
var val = await event.data()['TotalClassesTook'];
return val;
});
totalClassesTook = await totalClassesTook == null ? 0 : totalClassesTook;
totalClassesAttended =
await tutor_details.doc(uid).snapshots().map((event) async {
var val = await event.data()['TotalClassesAttended'];
return val;
});
totalClassesAttended =
await totalClassesAttended == null ? 0 : totalClassesAttended;
return percentage =
await ((totalClassesAttended / totalClassesTook) * 100) / 100;
} catch (e) {
return percentage = 0.0;
}
}
Calling the above function in the body from here :
body: Center(
child: Padding(
padding: EdgeInsets.symmetric(vertical: 150.0),
child: FutureBuilder(
future: displayPercentage(),
builder: (context, snapshot) {
return new CircularPercentIndicator(
radius: 120.0,
lineWidth: 13.0,
animation: true,
percent: snapshot.data,
center: new Text(
"${snapshot.data}",
style: new TextStyle(
fontWeight: FontWeight.bold, fontSize: 20.0),
),
footer: Padding(
padding: EdgeInsets.symmetric(
horizontal: 10.0, vertical: 10.0),
child: new Text(
"Attendance Percentage",
style: new TextStyle(
fontWeight: FontWeight.bold, fontSize: 17.0),
),
),
circularStrokeCap: CircularStrokeCap.round,
progressColor: Colors.purple,
);
}),
),
),
Output
======== Exception caught by widgets library ===========================
The following NoSuchMethodError was thrown building FutureBuilder(dirty, state: _FutureBuilderState#bfce6): The method '<' was called on null. Receiver: null Tried calling: <(0.0)
In builder
put an if
condition to check snapshot.hasData
.
builder: (context, snapshot) {
if (snapshot.hasData) {
// return CircularPercentIndicator here.
},
return Text('No Data');
},