[Flutter] Firebase core

2023-03-18 hit count image

Let's see how to use firebase_core to connect Firebase in Flutter

Outline

in this blog post, I will introduce how to use firebase_core to connect Firebase in Flutter.

Blog series

This blog post is a series. You can see the other posts on the link below.

Create Firebase Project

Next, we need to create a Google Firebase project. Click the link below to go to Google Firebase.

google firebase

Click SIGN IN button on the right top.

google firebase after login

After login, click GO TO CONSOLE to go to Google Firebase Console.

google firebase console

Click + Add project button to create a new porject on Google Firebase Console.

google firebase console add project

On the screen above, insert a project name that you want to use to Enter your project name. After inserting, click Continue button on the bottom to go to the next step.

google firebase console add google analytics

After inserting the project name, you can see the screen that asks you want to integrate Google Analytics. If you don’t want to integrate, click the switch to make Disable and create Fireabase project.

If you want to integreate Google Analytics, click Continue button.

google firebase console add integrate google analytics

Select Google Analytics account, and click Create project button to create Firebase project.

iOS configuration

Let’s see how to configure firebase_core on iOS to use Firebase in Flutter.

Change bundle identifier

Before creating iOS porject in Firebase, we need to change Bundle identifier on iOS. Execute ios/Runner.xcworkspace file to open Xcode.

change ios bundle id

Select the project name on left top and go to the General, you can find Bundle Identifier on it. Change the Bundle ID for your project.

Configure Firbase iOS project

When you select the project on Google Fireabse Console, you can see the screen like below.

google firebase console project

Click iOS button on the center of the screen to go iOS configuraion.

google firebase console project ios

Insert iOS Bundle ID, and click Register app button.

GoogleService-Info.plist download

Download GoogleService-Info.plist file created by Google Firebase, and drag it to the Runner/Runner folder to copy it on Xcode. After adding GoogleService-Info.plist file, click Next button.

add Firebase SDK

When you see the screen like below, click the Next button to go to the next page.

edit appdelegate.m for firebase

When you see the screen like below, click the Next button to go to the next page.

connect firebase to app

I juse clicked the Skip this step button to skip this part.

Android Configuration

Next, let’s see how to configure Android to use react-native-fireabse.

Modify Gradle

TO use Firebase in Flutter, we need to modify the Gradle file. First, open android/app/build.gradle file and add the code below.

...
apply plugin: 'com.google.gms.google-services' // <<<<<<<<<<<<< Add this

android {
  ...
}

And modify applicationId for your project.

// applicationId "com.example.blaboo_app"
applicationId "io.github.dev.yakuza.blaboo"

And then, open android/build.gradle file and modify it like below.

buildscript {
    ...
    dependencies {
        ...
        classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"
        classpath 'com.google.gms:google-services:4.3.14' // <<<<<<<<<<<<<<<< Add this
    }
}

Done! we’ve ready to use Firebase on Android.

Firbase 안드로이드 프로젝트 설정

Click Project Overview on the top of Google Firebase Console.

Google Firebase Console Project Overview

Click + Add app > Android icon to go Android project settings.

Google Firebase Android app register

Insert Android Package Name and click Register app button.

Google Firebase google-services.json setting

Copy and paste google-services.json to android/app folder and click Next button. Done. we’ve ready to use Firebase on Android. Click the Next button on all screens after.

Google Firebase setting on android

Install firebase_core

To use Firebase in Flutter, we need to install the firebase_core package. Execute the command below to install firebase_core.

flutter pub add firebase_core

iOS installation

To use firebase_core in iOS, we need to modify the ./ios/Podfile file and install required libraries. firebase_core requires the iOS version 11, so open the ./ios/Podfile file and modify it like the following.

# Uncomment this line to define a global platform for your project
platform :ios, '11.0'
...

And the, execute the command below to install required libraries.

# cd ios
pod install

Initialize Firebase

After installing the firebase_core pacakge, we need to initialize Firebase by using this pacakge. Open the main.dart file and modify it like below to initialize Firebase.

import 'package:firebase_core/firebase_core.dart';

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

  runApp(MyApp());
}

Test code

To write the test code of FirebaseCore, you need to install the mockito package.

Execute the following command to install the mockito package.

flutter pub add mockito

And then, you need to make the mock of FirebaseCore like the following.

import 'package:firebase_core_platform_interface/firebase_core_platform_interface.dart';
import 'package:flutter_test/flutter_test.dart';
import 'package:mockito/mockito.dart';
import 'package:plugin_platform_interface/plugin_platform_interface.dart';

class MockFirebaseCore extends Mock
    with
        // ignore: prefer_mixin, plugin_platform_interface needs to migrate to use `mixin`
        MockPlatformInterfaceMixin
    implements
        FirebasePlatform {
  @override
  FirebaseAppPlatform app([String name = defaultFirebaseAppName]) {
    return super.noSuchMethod(
      Invocation.method(#app, [name]),
      returnValue: FakeFirebaseAppPlatform(),
      returnValueForMissingStub: FakeFirebaseAppPlatform(),
    );
  }

  @override
  Future<FirebaseAppPlatform> initializeApp({
    String? name,
    FirebaseOptions? options,
  }) {
    return super.noSuchMethod(
      Invocation.method(
        #initializeApp,
        const [],
        {
          #name: name,
          #options: options,
        },
      ),
      returnValue: Future.value(FakeFirebaseAppPlatform()),
      returnValueForMissingStub: Future.value(FakeFirebaseAppPlatform()),
    );
  }

  @override
  List<FirebaseAppPlatform> get apps {
    return super.noSuchMethod(
      Invocation.getter(#apps),
      returnValue: <FirebaseAppPlatform>[],
      returnValueForMissingStub: <FirebaseAppPlatform>[],
    );
  }
}

class FakeFirebaseAppPlatform extends Fake implements FirebaseAppPlatform {}

This code is from GitHub of FirebaseCore.

Create the mocks/mock_firebase_core.dart file and copy-paste the code to it. And then, write the test code like the following.

import 'package:mockito/mockito.dart';
import 'mocks/mock_firebase_core.dart';
...

void main() {
  TestWidgetsFlutterBinding.ensureInitialized();

  const testAppName = 'testApp';
  const FirebaseOptions testOptions = FirebaseOptions(
    apiKey: 'apiKey',
    appId: 'appId',
    messagingSenderId: 'messagingSenderId',
    projectId: 'projectId',
  );
  final mockFirebaseCore = MockFirebaseCore();

  setUp(() {
    clearInteractions(mockFirebaseCore);
    Firebase.delegatePackingProperty = mockFirebaseCore;
    final FirebaseAppPlatform platformApp =
        FirebaseAppPlatform(testAppName, testOptions);

    when(mockFirebaseCore.initializeApp()).thenAnswer((_) {
      return Future.value(platformApp);
    });
  });

  estWidgets('FirebaseCore is initialized', (WidgetTester tester) async {
    await app.main();

    verify(mockFirebaseCore.initializeApp()).called(1);
  });
}

I just check the initializeApp function of FirebaseCore is called in the test code.

Completed

Finished! we’ve prepared the Flutter and Firebase project to use Firebase in Flutter, and seen how to configure the firebase_core package. To use the Firebase features, see other blog posts on below.

Was my blog helpful? Please leave a comment at the bottom. it will be a great help to me!

App promotion

You can use the applications that are created by this blog writer Deku.
Deku created the applications with Flutter.

If you have interested, please try to download them for free.

Posts