Firebase for Flutter in DartPad
Tags: flutter, flutterdev, firebase, programming
Published: 2021-11-11 13:02:06

---
title: Firebase for Flutter in DartPad
published: true
description: How to setup Firebase for Flutter in DartPad.
tags: flutter,flutterdev,firebase,programming
//cover_image: https://direct_url_to_image.jpg
---

During the [Firebase Summit 2021 Keynote](https://www.youtube.com/watch?v=BlMZ0XK8ZOI&t=1s) Firebase announced the support for its Flutter SDKs in [DartPad](https://dartpad.dev/). 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](https://firebase.google.com/docs) 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](https://firebase.google.com/docs/web/setup). 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/mifcqx324ppxbg0v7exa.png)
 
## 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](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/d6ftunt3regmo0bh2nbv.png)

## Initialize Firebase

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

```dart
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());
}
``` 

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](https://firebase.google.com/docs/firestore) as an example here, but there are other Firebase APIs you can use in DartPad as well, such as [Firebase Authentication](https://firebase.google.com/docs/auth). Say you have a collection of 'people' that you want to display in your DartPad app.

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/5fw7utqwa1ukrbtmy8py.png)

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

```dart
// 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']),
            );
          },
        );
      },
    );
  }
}
``` 

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

![Image description](https://dev-to-uploads.s3.amazonaws.com/uploads/articles/w3zq5z7x41pxkfs0p6wb.png)

## 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](https://dartpad.dev/)! 

## Code sample

If you'd like to see the full sample for this article to experiment with, it's available [here](https://dartpad.dev/b7e373d4fc0ef66d97edcf90bbc48328).

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](https://firebase.google.com/docs/firestore/security/get-started). 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.