Flutter web unable to get data from firestore

604

Solution 1

By changing all versions in index.html to:-

  <script src="https://www.gstatic.com/firebasejs/7.20.0/firebase-firestore.js"></script>
  <script src="https://www.gstatic.com/firebasejs/7.20.0/firebase-analytics.js"></script>
  <script src="https://www.gstatic.com/firebasejs/7.20.0/firebase-storage.js"></script>

Not just firebase-storage version:-

<script src="https://www.gstatic.com/firebasejs/7.20.0/firebase-storage.js"></script>

I know it's kinda stupid that I had put up a question for this, but yeah, now it works.

Solution 2

This may be because you forgot to add Firestore rules to allow fetching from your collection. I suggest that you check if there was an error fetching the snapshot. You can do this by adding to your code:

if (snapshot.hasError) { print(snapshot.error.toString()) }

Share:
604
Illuminate
Author by

Illuminate

Updated on December 29, 2022

Comments

  • Illuminate
    Illuminate over 1 year

    I'm having a problem getting my data from firestore, here's the code:-

    import 'package:cloud_firestore/cloud_firestore.dart';
    import 'package:flutter/material.dart';
    import 'package:machineweb/model/models.dart';
    
    
    
    class ProductArgs {
      String crop;
      ProductArgs({this.crop});
    }
    
    class ShowProduct extends StatefulWidget {
      static String route = '\showproductroute';
      @override
      _ShowProductState createState() => _ShowProductState();
    }
    
    class _ShowProductState extends State<ShowProduct> {
      @override
      Widget build(BuildContext context) {
        double screenWidthSize = MediaQuery.of(context).size.width;
        double height = MediaQuery.of(context).size.height;
        ProductArgs args = ModalRoute.of(context).settings.arguments;
    
        FirebaseFirestore firestore = FirebaseFirestore.instance;
    
        List<DocumentSnapshot> products = []; // stores fetched products
    
        bool isLoading = false; // track if products fetching
    
        bool hasMore = true; // flag for more products available or not
    
        int documentLimit = 2; // documents to be fetched per request
    
        DocumentSnapshot
            lastDocument; // flag for last document from where next 10 records to be fetched
    
        ScrollController _scrollController = ScrollController();
    
        print(args.crop);
    
        getProducts() async {
          if (!hasMore) {
            print('No More Products');
            return;
          }
          if (isLoading) {
            return;
          }
          setState(() {
            isLoading = true;
          });
          QuerySnapshot querySnapshot;
          if (lastDocument == null) {
            querySnapshot = await firestore
                .collection('productData')
                .where('type', isEqualTo: args.crop)
                .limit(documentLimit)
                .get();
          } else {
            querySnapshot = await firestore
                .collection('productData')
                .where('type', isEqualTo: args.crop)
                .startAfterDocument(lastDocument)
                .limit(documentLimit)
                .get();
            print(1);
          }
          if (querySnapshot.docs.length < documentLimit) {
            hasMore = false;
          }
          lastDocument = querySnapshot.docs[querySnapshot.docs.length - 1];
          products.addAll(querySnapshot.docs);
          setState(
            () {
              isLoading = false;
            },
          );
        }
    
        _scrollController.addListener(
          () {
            double maxScroll = _scrollController.position.maxScrollExtent;
            double currentScroll = _scrollController.position.pixels;
            double delta = MediaQuery.of(context).size.height * 0.20;
            if (maxScroll - currentScroll <= delta) {
              getProducts();
            }
          },
        );
    
        int _crossAxisCount = 0;
    
        if (screenWidthSize > 720) {
          _crossAxisCount = 3;
        } else if (screenWidthSize > 520) {
          _crossAxisCount = 2;
        } else {
          _crossAxisCount = 1;
        }
    
        print(products.length.toString());
    
        return Container(
          child: Column(children: [
            Expanded(
              child: products.length == 0
                  ? Center(
                      child: Text('No Data...'),
                    )
                  : ListView.builder(
                      controller: _scrollController,
                      itemCount: products.length,
                      itemBuilder: (context, index) {
                        return ListTile(
                          contentPadding: EdgeInsets.all(5),
                          title: Text(products[index].data()['name']),
                          subtitle: Text(products[index].data()['short_desc']),
                        );
                      },
                    ),
            ),
            isLoading
                ? Container(
                    width: MediaQuery.of(context).size.width,
                    padding: EdgeInsets.all(5),
                    color: Colors.yellowAccent,
                    child: Text(
                      'Loading',
                      textAlign: TextAlign.center,
                      style: TextStyle(
                        fontWeight: FontWeight.bold,
                      ),
                    ),
                  )
                : Container()
          ]),
        );
      }
    }
    

    products.lenght is zero even if there is data on firestore.

    Here's my index.html:-

      <script src="https://www.gstatic.com/firebasejs/8.3.1/firebase-auth.js"></script>
      <script src="https://www.gstatic.com/firebasejs/8.3.1/firebase-firestore.js"></script>
      <script src="https://www.gstatic.com/firebasejs/8.3.1/firebase-analytics.js"></script>
      <script src="https://www.gstatic.com/firebasejs/8.3.1/firebase-storage.js"></script>
    

    even tried changing it to:-

    <script src="https://www.gstatic.com/firebasejs/7.20.0/firebase-storage.js"></script>
    

    How do I get data from firestore, I tried using other packages even that didn't work.

    Any solutions, there are many similar question but it's not solving by problem?

    • Saurabh K. Sharma
      Saurabh K. Sharma about 3 years
      Have you initialize the firebase web? firebase.flutter.dev/docs/installation/web
    • Illuminate
      Illuminate about 3 years
      I'm able to write data but can't read it @SaurabhK.Sharma, and yes I have initialize it.
    • Saurabh K. Sharma
      Saurabh K. Sharma about 3 years
      Please check your firestore rules. plus share the error you are getting when you read it.
    • Illuminate
      Illuminate about 3 years
      There is no error, If user id is not null it allow read and [email protected]
    • persec10000
      persec10000 almost 3 years
      Snapshot Error is following. snapshot Error:[cloud_firestore/unknown] NoSuchMethodError: invalid member on null: 'includeMetadataChanges' How can I fix the issue? Thanks.
  • persec10000
    persec10000 almost 3 years
    Snapshot Error is following. snapshot Error:[cloud_firestore/unknown] NoSuchMethodError: invalid member on null: 'includeMetadataChanges' How can I fix the issue?
  • persec10000
    persec10000 almost 3 years
    I could fix my issue by updating Firebase JS SDK version from 8.1 to 7.22.1 in index.html Please refer following article. Thanks. stackoverflow.com/questions/65001207/…