Flutter web unable to get data from firestore

Viewed 753

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?

2 Answers

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()) }

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.

Related