Flutter Web – Fetching Firestore collection

Issue

I have a flutter mobile app which works really great, but when trying to migrate the same code to flutter web, I am unable to fetch data from FireStore using . It’s like the StreamBuilder does not want to work in web mode, but will work only for mobile app mode.

At the top of the dart file, I’ve imported:

'package:cloud_firestore/cloud_firestore.dart'
'package:firebase_auth/firebase_auth.dart'

and the below code, is the snippet showing the streambuilder and listview. In web mode, the code gets stuck at if (!snapshot.hasData) condition and only returns text ‘Loading…’ to my Chrome browser. While in the mobile app, it works as expected and returns a listview with all data from firestore.

Container(
height: safeBlockVertical * 0.9,
child: StreamBuilder(
                              
  stream: FirebaseFirestore.instance.collection(orgName).snapshots(),
  builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) {
                                
    if (!snapshot.hasData) {return new Text('Loading...');} else {
                                
      return ListView(
        children: snapshot.data.docs.map(
        (DocumentSnapshot document) {
             .
             .
             .
             child: ListTile(
               title: ....
               trailing: ....
               onTap: () {}

Initially I thought the firebase configuration in index.html might be wrong and fiddled around with it a lot. But later realized that that’s not the case since I was able to login and fetch user information successfully from firestore without any error. So the firebase configuration is good, now I am wondering that the above StreamBuilder probably does not work on Flutter Web. Is that the case? Any help?

Solution

There are a few points that are different between mobile and web usage of firebase in flutter but there is no clear documentation on that.

First issue is the import of firebase scripts in the html as the default version recommended by firebase when creating the web app doesn’t seem to work.
This is a version I have used and it does work.

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

Second, the packages you can use in your pubspec.yaml file is a bit different. Here is what I use and does work :

  firebase_web: ^5.0.9

It includes storage and Firestore functionalities. There might be a few syntax differences but you can find out about them with a few searches.

Good luck coding!

Answered By – amirala7

Answer Checked By – Gilberto Lyons (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.