DEV Community

Fré Dumazy
Fré Dumazy

Posted on

Firebase for Flutter in DartPad

During the Firebase Summit 2021 Keynote Firebase announced the support for its Flutter SDKs in DartPad. This is something that provides a lot of opportunities and will definitely make it easier to experiment with both Firebase as well as Flutter. Even though the setup is pretty straight forward, I'd like to show it step by step.

Firebase setup

I don't want to go into too much detail about how to setup a project in Firebase since there's already a lot more resources on that and their own documentation provides everything you need to know. The important thing to know is that you need to have a Firebase project and have a web app registered. If you go into the project settings and down to 'Your apps', you can select the 'Config' option in the 'SDK setup and configuration'. This gives a clear overview of the values you'll need.

Image description

DartPad

In DartPad, start by displaying the "Pub package versions" by clicking on the ℹ️ in the bottom right corner. This will show all the packages that you can import in DartPad. You should be able to see the firebase_* packages listed. If you're experiencing issues, this can be a good reference to know which version of these you are actually using.

Image description

Initialize Firebase

Initializing the Firebase SDK is almost only a matter of copying your web app's configuration into the FirebaseOptions:

import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: const FirebaseOptions(
      apiKey: "AIzaAbCdEf...",
      authDomain: "my-project-id.firebaseapp.com",
      projectId: "my-project-id",
      storageBucket: "my-project-id.appspot.com",
      messagingSenderId: "012345678912",
      appId: "1:012345678912:web:abc123...",
    ),
  );

  runApp(MyApp());
}
Enter fullscreen mode Exit fullscreen mode

There are 3 steps in this process:

  1. Call WidgetsFlutterBinding.ensureInitialized(); to avoid calls to the framework before it's actually ready.

  2. Initialize the Firebase SDK with the values that are found in the Firebase Console under your web app's configuration. Depending on your app, it's probably important that you await this before moving on to the last step.

  3. The last step is simply running your initial widget with the runApp() function.

Calling the Firebase SDK

Now you just need to verify if this is correct. I'll use Cloud Firestore as an example here, but there are other Firebase APIs you can use in DartPad as well, such as Firebase Authentication. Say you have a collection of 'people' that you want to display in your DartPad app.

Image description

Then the code you'll need is nothing different than using the Firebase SDK for Flutter on another platform.

// new import to add
import 'package:firebase_core/firebase_core.dart';

// main method as shown above

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        body: Center(
          child: PeopleList(),
        ),
      ),
    );
  }
}

class PeopleList extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return StreamBuilder<QuerySnapshot<Map<String, dynamic>>>(
      stream: FirebaseFirestore.instance.collection('people').snapshots(),
      builder: (context, snapshot) {
        if (!snapshot.hasData) {
          return const CircularProgressIndicator();
        }
        final docs = snapshot.requireData.docs;
        return ListView.builder(
          itemCount: docs.length,
          itemBuilder: (_, index) {
            final json = docs[index].data();
            return ListTile(
              title: Text(json['firstName']),
              subtitle: Text(json['lastName']),
            );
          },
        );
      },
    );
  }
}
Enter fullscreen mode Exit fullscreen mode

As a result, the people are listed when running the app.

Image description

Conclusion

Setting up the Firebase SDK in DartPad is really easy and actually takes less steps than using it on another platform. I can see this having huge benefits for teaching and sharing samples. Give it a try at dartpad.dev!

Code sample

If you'd like to see the full sample for this article to experiment with, it's available here.

You'll need to use your own Firebase web app config and make sure you have the 'people' collection available as shown in the example above.

Other notes

  • I'm not a 100% sure that you need to call WidgetsFlutterBinding.ensureInitialized(); as the initial step. In this example it works fine without, but I added it because more complex use cases might require it.

  • If you start a new Firebase project and Cloud Firestore to test this and you're not able to fetch the data, check your security rules. I've set mine to test mode for this article but this might not be the case for you.

  • This tutorial only focuses on the minimum to set up Firebase on DartPad. There might be better ways to call the Firestore APIs or to structure the code.

Top comments (3)

Collapse
 
ankita_tripathi_5cdae815b profile image
Ankita Tripathi

This is unbelievable. So much on point and quick with the update. Would you like to share this with Google's Dev Library too? devlibrary.withgoogle.com/

Collapse
 
dumazy profile image
Fré Dumazy

Thanks :) I wasn't aware of Google's Dev Library, I'll submit it there

Collapse
 
ankita_tripathi_5cdae815b profile image
Ankita Tripathi

Your article is selected! Congratulations🥁