skip to Main Content

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


  1. Instead of this

    late DiaryFirebaseCloudStorage _diaryRepository;
    late var _createdDiariesInThePast30Days;
    

    Use this

    DiaryFirebaseCloudStorage? _diaryRepository;
    var _createdDiariesInThePast30Days;
    
    Login or Signup to reply.
  2. You have declared variables as late however you didn’t initialize them before the build function started execution. Instead, convert all your late variables to nullable types.

    // From 
    late var _createdDiariesInThePast30Days;
    
    // To
    
    // Because your function returns Future<int> change it to nullable int (int?)
    int? _createdDiariesInThePast30Days;
    
    // Or pre-initialize it with some value like 0
    int _createdDiariesInThePast30Days = 0;
    
    

    This should resolve your issue, let me know if you are still facing issues.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search