DEV Community

Cover image for Flutter Web: Firestore CRUD
happyharis
happyharis

Posted on • Edited on

Flutter Web: Firestore CRUD

Updated [21/08/2020]: cloud_firestore major changes

Now, all Flutter Firebase documentation is in the new link: https://firebase.flutter.dev/docs/overview

Firstly, import the latest cloud_firestore and firebase core dependency in your pubspec.yaml file:

In pubspec.yaml...

dependencies:
  cloud_firestore: <latest version>
  firebase_core: <latest version>

Secondly, add the Firebase and Firestore JS SDK in your web/index.html file:

In index.html...

<body>
    <script src="https://www.gstatic.com/firebasejs/7.9.1/firebase-app.js"></script>
    <script src="https://www.gstatic.com/firebasejs/7.9.1/firebase-firestore.js"></script>
    <script src="main.dart.js" type="application/javascript"></script>
</body>

Third, initialise Firebase, also in your index.html file with the Firebase keys (that can be found in Firebase settings):

In index.html...

<body>
  <!-- Previously loaded Firebase SDKs -->

  <!-- ADD THIS BEFORE YOUR main.dart.js SCRIPT -->
  <script>
    // TODO: Replace the following with your app's Firebase project configuration.
    // See: https://support.google.com/firebase/answer/7015592
    var firebaseConfig = {
      apiKey: "...",
      authDomain: "[YOUR_PROJECT].firebaseapp.com",
      databaseURL: "https://[YOUR_PROJECT].firebaseio.com",
      projectId: "[YOUR_PROJECT]",
      storageBucket: "[YOUR_PROJECT].appspot.com",
      messagingSenderId: "...",
      appId: "1:...:web:...",
      measurementId: "G-..."
    };
    // Initialize Firebase
    firebase.initializeApp(firebaseConfig);
  </script>
  <!-- END OF FIREBASE INIT CODE -->

  <script src="main.dart.js"></script>
</body>

Lastly, initialise firebase in your flutter main.dart file

import 'package:flutter/material.dart';

// Import the firebase_core plugin
import 'package:firebase_core/firebase_core.dart';

void main() {
  runApp(App());
}

class App extends StatelessWidget {
  // Create the initilization Future outside of `build`:
  final Future<FirebaseApp> _initialization = Firebase.initializeApp();

  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      // Initialize FlutterFire:
      future: _initialization,
      builder: (context, snapshot) {
        // Check for errors
        if (snapshot.hasError) {
          return SomethingWentWrong();
        }

        // Once complete, show your application
        if (snapshot.connectionState == ConnectionState.done) {
          return MyAwesomeApp();
        }

        // Otherwise, show something whilst waiting for initialization to complete
        return Loading();
      },
    );
  }
}

*Code above was from FlutterFire documentation

And TADA! You're free to use firestore CRUD functions whenever you like, in your mobile app, and web app as per usual.

import 'package:cloud_firestore/cloud_firestore.dart';

FirebaseFirestore.instance.collection('diaries').add(data)

FirebaseFirestore.instance.collection('diaries').doc('monday').update(data)

FirebaseFirestore.instance.collection('diaries').doc('monday').delete()

Top comments (22)

Collapse
 
emailsubjekt profile image
emailsubjekt

Hi, this doesn't work in deploy mode. It works only in test mode, when testing in Android Studio. When you deploy the app to the web so it has a URL everyone can see, all you get is a blank webpage with nothing on it. Please advise how to fix that.

Collapse
 
happyharis profile image
happyharis

Try inspecting your website and see what's the error. To inspect: right click on the white screen and click inspect. Then go to the tab console and see the error. Don't reply this thread with your errors. If you can't fix the error, go to flutter github issue and create a new issue with your error.

Collapse
 
vewapps profile image
VEWapps

Does it work if you initialize the app in the index.html file instead of the main.dart file? That fixed a similar problem for me in a different app.

Collapse
 
happyharis profile image
happyharis

When you say initialise, you mean you are on debug mode? I'm not too sure about it, but if you want to debug, it will be tedious process.

Thread Thread
 
vewapps profile image
VEWapps

I may have used the wrong words. What I meant was to put:

var firebaseConfig = {
apiKey: "",
authDomain: "",
databaseURL: "",
projectId: "",
storageBucket: "",
messagingSenderId: "",
appId: "",
measurementId: ""

};

firebase.initializeApp(firebaseConfig);
firebase.analytics();

in the index.html file instead of putting:

Future main() async {
if (Firebase.apps.isEmpty) {
print(Firebase.apps);
Firebase.initializeApp(
apiKey: '',
authDomain: '',
databaseURL: '',
projectId: '',
storageBucket: '',
messagingSenderId: '',
appId: '',
);
}

in the main.dart file.

Thread Thread
 
vewapps profile image
VEWapps

You know what though? It is working fine for me with the app config stuff in the main.dart file, so I doubt that what I suggested will fix your problem, but maybe you (emailsubjekt) will stumble across it if you keep trying.

Thread Thread
 
happyharis profile image
happyharis

Thanks for helping out VEWapps 😊

Collapse
 
genovoxx profile image
genovoxx

Hi happyharis,

thanks for this tutorial, this was already very helpful. Would you mind sharing the source code of your tutorial since I was not able to follow every step in the video.
Thanks so much for your help!

Collapse
 
happyharis profile image
happyharis

Sorry for the late reply! github.com/happyharis/linktree_dem... Hope this helps

Collapse
 
genovoxx profile image
genovoxx • Edited

You made my day. Now it works! Thank you so much!

Maybe you have an idea how I could additionally get the documentID of the mapped documents?

Collapse
 
danielreuven profile image
danielreuven

firestore.collection('names').doc("uid").set({
'text': "gfghghgh",
}).catchError((e) {
print(e);
});

Collapse
 
jooaos profile image
João Victor

Hi, how can I get a subcollection whith this method?

Collapse
 
happyharis profile image
happyharis

firestore.collection('names').doc('111').collection('links')

Collapse
 
jooaos profile image
João Victor

Sorry, I didn't explain it well. In my application I have a list, a list as if it were from your linktree application. Each item in the list has its subcollections, and I want to click on the item to bring up a new screen with subcollections. If I use as you answered here, I will always have the same values ​​as the subcollection

Thread Thread
 
happyharis profile image
happyharis
Collapse
 
kabirkwatra profile image
Kabir Kwatra

Wait. Why not just add the firebase package as a dependency?

Collapse
 
happyharis profile image
happyharis

The firebase package is only available for flutter web. Firebase core however, can be used for iOs, Android and Web.

Collapse
 
kabirkwatra profile image
Kabir Kwatra

But these firestore functions won't run on mobile, will they?

Thread Thread
 
happyharis profile image
happyharis

just tried it on mobile iOS simulator, it doesn't work.

Collapse
 
suvarna84 profile image
suvarna84

Hi, i am not able to see the data in the firebase database, please tell me what i am doing wrong.

Collapse
 
eliudio profile image
eliudio

Great Haris! Thanks

Collapse
 
larrybauman profile image
LarryBauman

Anyone else having trouble getting this to work? In Debug mode all Firestore and QuerySnapshot both return an error NoSuchMethodError: The getter 'uri' was called on null.