I tried Firebase Local Emulator Suite in Flutter

Introduction

Recently, I was doing personal development with Flutter × Firebase, and I suddenly found something like this, so I think I'll give it a try: sunglasses:

Reference: [Overview of Firebase Local Emulator Suite](https://firebase.google.com/docs/emulator-suite?hl=ja)

environment

Prerequisites

--You can run the flutter command on terminal --Flutter settings for each editor are complete

Create a foundation

Create a Flutter project

#Create a project
cd {Where you want to create a project}
flutter create --org {package name} {Project name}

#Keep your project versioned
cd {Project name}
git init --initial-branch main

#Incorporate beta version of gitignore into your local project
echo "$(curl -fsSL https://raw.githubusercontent.com/flutter/flutter/beta/.gitignore)" >> .gitignore

# GoogleService-Info.Avoid versioning plist
echo "**/ios/**/GoogleService-Info.plist" >> .gitignore

#Commit all changes
git add .
git commit -m "initial commit"

Create a Firebase project

Before you can use the Firebase Local Emulator Suite, you need to create a Firebase project and configure the required settings. Personally, I hope this setting is no longer necessary lol

Add a project in the Firebase Console (https://console.firebase.google.com/)

Add a project with a suitable name.

1 2 3 4

Add an app to your project

This time, we will only run the iOS simulator, so we will not set up Android. Reference: Add Firebase to Flutter App

Until GoogleService-Info.plist is set

1 2 3 4 5
Check and enter the bundle ID in Xcode GoogleService-Info.Download plist and Runner/Move to Runner directory Do nothing and click Next Do nothing and click Next Click Go to Console

Add FlutterFire plugin

pubspec.yaml


...
dependencies:
  flutter:
    sdk: flutter

+ # For Firebase
+ firebase_core: ^0.5.3
+ firebase_database: ^4.4.0
...
#Update library
cd {Where the project was created}
flutter pub get

#Commit all changes
git add .
git commit -m "add FlutterFire"

Docker settings

Use Docker to reduce environment-dependent things as much as possible: whale:

Create Dockerfile

cd {Where the project was created}
mkdir -p docker/firebase
touch ./docker/firebase/Dockerfile

Dockerfile


FROM ubuntu:20.04

RUN apt-get update -y

RUN apt-get install -y curl openjdk-11-jre-headless

RUN curl -sL https://deb.nodesource.com/setup_14.x | bash - \
    && apt-get install -y nodejs

RUN npm install -g firebase-tools
#Commit all changes
cd {Where the project was created}
git add .
git commit -m "add Dockerfile"

Create docker-compose.yaml

cd {Where the project was created}/docker
touch docker-compose.yaml

docker-compose.yaml


version: "3"

services:
    firebase:
        build:
            context: ./firebase
        volumes:
            - ./firebase/emulators/:/opt/workspace:cached
            - ./firebase/bin/:/root/.cache:cached
            - ./firebase/config/:/root/.config:cached
        ports:
            - 4000:4000 # Emulator Suite UI
            - 9000:9000 # Realtime Database
        working_dir: /opt/workspace
        command: bash
        tty: true
#Commit all changes
cd {Where the project was created}
git add .
git commit -m "add docker-compose.yaml"

Firebase CLI settings

#Start container
cd {Where the project was created}/docker
docker-compose up -d

#Enter the container
docker-compose exec firebase bash
#After hitting the command, select which user to log in with the browser
#After logging in, paste the key into terminal
firebase login --no-localhost

#After hitting the command, you will be asked various things, so proceed while checking each one
firebase init

Launch Local Emulator Suite

Edit {location where the project was created} /docker/firebase/emulators/firebase.json as follows.

firebase.json


{
  "rulesFile": "database.rules.json",
  "emulators": {
    "database": {
      "host": "0.0.0.0",
      "port": 9000
    },
    "ui": {
      "enabled": true,
      "host": "0.0.0.0",
      "port": 4000
    }
  }
}
#Commit all changes
cd {Where the project was created}
git add .
git commit -m "complete firebase init"

Then launch the Local Emulator Suite from inside the container!

firebase emulators:start

If you haven't customized the port number in particular, you should be able to see something like this: thumbsup:

http://localhost:4000 http://localhost:4000/database

Access data from the Flutter app

Database access rule settings

By default, no one can change the database, so edit {where the project was created} /docker/firebase/emulators/database.rules.json as follows:

json:database.rules.json


{
  "rules": {
    ".read": true,
    ".write": true
  }
}
#Commit all changes
cd {Where the project was created}
git add .
git commit -m "edit database.rules.json"

Create and get data from the Flutter app

Edit {location where the project was created} /lib/main.dart as follows.

main.dart


import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_database/firebase_database.dart';
import 'package:firebase_database/ui/firebase_animated_list.dart';
import 'package:flutter/material.dart';

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Local Emulator Suite Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(title: 'Local Emulator Suite Demo'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  // TODO:databaseURL specifies your local URL
  final _databaseReference = FirebaseDatabase(
    app: Firebase.app(),
    databaseURL: 'http://127.0.0.1:9000/?ns=fir-emulator-demo-48f2b',
  ).reference();

  void _addItem() {
    _databaseReference.push().set('add item');
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: FirebaseAnimatedList(
        query: _databaseReference.orderByKey(),
        padding: const EdgeInsets.all(8.0),
        reverse: false,
        itemBuilder: (_, snapshot, animation, x) {
          return ListTile(
            title: Text(snapshot.value.toString()),
          );
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _addItem,
        child: Icon(Icons.add),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

Don't forget to commit

#Commit all changes
cd {Where the project was created}
git add .
git commit -m "edit main.dart"

Try it with the Flutter app

Very convenient! test.gif

in conclusion

This time, I used Docker, so there are quite a lot of setting items lol However, if you do this, you can perform the test separately from the production environment, so I think that CI/CD settings should be included in personal development: sunglasses:

I wrote it all at once at midnight, so if you write something strange, it would be helpful if you could let me know in the comments: bow: lol

Put the final code here [https://github.com/blendthink/firebase_emulator_demo).

Please give it a try!

Recommended Posts

I tried Firebase Local Emulator Suite in Flutter
I tried to implement Firebase push notification in Java
I tried metaprogramming in Java
I tried putting Domino11 in CentOS7
I tried using JWT in Java
I tried using Elasticsearch API in Java
I tried a calendar problem in Ruby
I tried the new era in Java
I tried to build a Firebase application development environment with Docker in 2020
I tried the AutoValue library in Intellij
I tried embedding a formula in Javadoc
[For beginners] I tried using DBUnit in Eclipse
I tried to implement polymorphic related in Nogizaka.
[For beginners] I tried using JUnit 5 in Eclipse
I tried to organize the session in Rails
I tried to implement deep learning in Java
I tried to output multiplication table in Java
I tried to develop an application in 2 languages
I tried Spring.
I tried tomcat
I tried youtubeDataApi.
I tried refactoring ①
I tried FizzBuzz.
I tried using a database connection in Android development
I tried Mastodon's Toot and Streaming API in Java
I tried to organize the cases used in programming
I tried using Google Cloud Vision API in Java
# 2 [Note] I tried to calculate multiplication tables in Java.
I tried to create a Clova skill in Java
I tried to make a login function in Java
I tried installing the Docker Integration plugin in IntelliJ
I tried calling Java / Objective-C native code from Flutter
I tried using an extended for statement in Java
I tried passing Java Silver in 2 weeks without knowing Java
I tried to implement the Euclidean algorithm in Java
~ I tried to learn functional programming in Java now ~
I tried to find out what changed in Java 9
I installed Squid on CentOS in my local environment
I tried to develop the cache function of Application Container Cloud Service in the local environment