I am having an issue displaying data from a API call.
the data is there because when I do hot reload the component works perfect.
here is the parent component::
class _ReportsState extends State<Reports> {
late DiaryFirebaseCloudStorage _diaryRepository;
late var _createdDiariesInThePast30Days;
@override
void initState() {
super.initState();
_diaryRepository = DiaryFirebaseCloudStorage();
setVariables();
}
setVariables() async {
_createdDiariesInThePast30Days =
await _diaryRepository.getCreatedDiariesBasedOnPreviousDays(30);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: PreferredSize(
preferredSize: Size.fromHeight(kToolbarHeight),
child: AppBarIconContainer(),
),
body: Column(children: [
Expanded(
child: GridView.count(
crossAxisCount: 2, // Number of boxes per row
children: [
SingleDigitReport(
number: _createdDiariesInThePast30Days.toString())
]))
]));
}
}
this is the class being used to get the data from firebase:::
class DiaryFirebaseCloudStorage {
final _diary = FirebaseFirestore.instance.collection('diary');
// final _user = FirebaseAuth.instance.currentUser!;
final _user = AuthHandler.getUser();
// Future<int>
getCreatedDiariesBasedOnPreviousDays(days) async {
print("getCreatedDiariesBasedOnPreviousDays()");
final now = DateTime.now();
final daysDelta = now.subtract(Duration(days: days));
final querySnapshot = await _diary
.where(createdByColumn, isEqualTo: _user.uid)
.where(createdOnColumn, isGreaterThan: daysDelta)
.get();
return querySnapshot.docs.length;
}
// singleton
static final DiaryFirebaseCloudStorage _shared =
DiaryFirebaseCloudStorage._sharedInstance();
DiaryFirebaseCloudStorage._sharedInstance();
factory DiaryFirebaseCloudStorage() => _shared;
}
what am I doing wrong?
here is a video of the issue::
https://youtu.be/lAqI7rwP-bE
this is the error:::
════════ Exception caught by widgets library ═══════════════════════════════════
The following LateError was thrown building Reports(dirty, state: _ReportsState#8004c):
LateInitializationError: Field '_createdDiariesInThePast30Days@561088100' has not been initialized.
The relevant error-causing widget was
Reports
hub.dart:70
When the exception was thrown, this was the stack
#0 _ReportsState._createdDiariesInThePast30Days (package:thraive/pages/reports/reports.dart)
reports.dart:1
#1 _ReportsState.build
reports.dart:46
#2 StatefulElement.build
framework.dart:5080
#3 ComponentElement.performRebuild
framework.dart:4968
#4 StatefulElement.performRebuild
I asked chatgpt and looked at other StackOverflow posts and I cant find anything!
2
Answers
Instead of this
Use this
You have declared variables as
late
however you didn’t initialize them before thebuild
function started execution. Instead, convert all yourlate
variables tonullable
types.This should resolve your issue, let me know if you are still facing issues.