Ad

How To Get Data From Firestore When Homepage Loads?

I am trying to make a todo list app with Flutter. When the homepage loads, the data does not appear on program

I tried QuerySnapshot, '.then', sleep and more but unfortunately none of them worked

I tried to debug and find where is the problem. It looks like while the program loads, the data from Firestore is not ready yet that is why it does not appear on the homepage.



import 'dart:async';
import 'package:flutter/material.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'dart:io';

class home extends StatefulWidget {
  static const String id = 'home';
  @override
  _homeState createState() => _homeState();
}

class _homeState extends State<home> {
  String userUid;
  FirebaseUser loggedInUser;
  final _fireStore = Firestore.instance;

  final _auth = FirebaseAuth.instance;
  List<Container> messageWidgets = [];

  void getCurrentUser() async {
    final user = await _auth.currentUser();
    if (user != null) {
      loggedInUser = user;
      userUid = loggedInUser.uid;
    }
  }

  getTasks() {
    print('///////////////Get tasks///////////////');
    return _fireStore
        .document('Userss')
        .collection('$userUid/Tasks')
        .getDocuments();
  }


  bool boool = false;
  var tasks;

  @override
  void initState() {
    getCurrentUser();
    getTasks().then((QuerySnapshot docs) {
      if (docs.documents.isNotEmpty) {
        boool = true;
        tasks = docs.documents[0].data;
      }
    });
    super.initState();
  }


  @override
  Widget build(BuildContext context) {
    return SafeArea(
        child: Center(
            child: Column(
      children: <Widget>[
        boool
            ? Column(
                children: <Widget>[
                  Text(tasks['Task']),
                  Text(tasks['Category']),
                ],
              )
            : Container(
                child: Text('No DATA'),
              ),
      ],
    )));
  }


I expect the data appears when homepage loads but it does not appear

Ad

Answer

My quick guess is that you need to use setState(), since the data is loaded from Firestore asynchronously.

So something like:

getTasks() {
  print('///////////////Get tasks///////////////');
  _fireStore
    .document('Userss')
    .collection('$userUid/Tasks')
    .getDocuments().then((QuerySnapshot docs) {
      if (docs.documents.isNotEmpty) {
        boool = true;
        setState(() {
          tasks = docs.documents[0].data;
        });
      }
    });
}
Ad
source: stackoverflow.com
Ad