Search code examples
fluttergoogle-cloud-firestorestream-builder

Streambuilder only showing data from local cache on first launch of app


I'm using StreamBuilder to stream data from firestore.

StreamBuilder<QuerySnapshot>(
    stream:  _firestore.collection('meals').where('email', isEqualTo: loggedInUser.email).orderBy('date', descending: true).snapshots(),

If i take out the .where section of the stream, it returns all data to the device. Once this has been done, I can then put the .where section back in and it works fine. However, it doesn't work straight away. This would suggest the .where section only works once the cache already has data. Also, if I add a document using firestore console, it doesn't update the app with the new data. But for some reason it will show all of the updated documents if i remove the .where part.

I'm really confused. Any ideas?

Thanks Jason

UPDATE: I've now figured out how to solve this problem. Please see my answer below for how I solved it.


Solution

  • I finally figured out the answer to my problem.

    I added queryUserData(); to the initState(). Here's how it looks in the code:

    class HomeScreen extends StatefulWidget {
      static const String id = 'home_screen';
    
      @override
      _HomeScreenState createState() => _HomeScreenState();
    }
    
    class _HomeScreenState extends State<HomeScreen> {
    
      final _firestore = Firestore.instance;
      final _auth = FirebaseAuth.instance;
      FirebaseUser loggedInUser;
    
      @override
      void initState() {
        super.initState();
        getCurrentUser();
        queryUserData();
      }
    
      void getCurrentUser() async {
        try {
          final user = await _auth.currentUser();
          if (user != null) {
            loggedInUser = user;
            print('this is a test${loggedInUser.email}');
          }
        } catch (e) {
          print(e);
        }
      }
    
      void queryUserData() async {
        final user = await _auth.currentUser();
        loggedInUser = user;
        final query = await _firestore.collection('meals').orderBy('date', descending: true).where('email', isEqualTo: '${loggedInUser.email}').getDocuments(source: Source.cache);
        var totalEquals = query.documents.length;
        print('$totalEquals records found for this user');
    
        if (totalEquals >= 1) {
          print(query);
          print('cache has data. Therefore data will now only be read from cache');
        } else {
          print('data will be read from firestore until you have at least 1 meal');
          getFirestoreInitialData();
    
        }
      }
    
      void getFirestoreInitialData() async {
        final query = await _firestore.collection('meals').getDocuments();
        print(query);
        print('data still being read from firestore');
      }