Firebase helps you develop, measure, improve, and evolve your mobile applications. It is supported by Google and covers a wide range of services including real-time databases, authentication, crash monitoring, analytics, push notifications and more. Firebase offers all of these back-end, platform-specific tools as a service, so you can focus more on building the core functionality of your application.

FlutterFire is an official plugin that enables you to implement Firebase services in your Flutter application. The stable version already provides a variety of key plug-ins, and more are expected in the near future.

In this tutorial, we will demonstrate how to integrate some of the most useful FlutterFire plug-ins, including.

  • certification
  • Cloud fire library
  • Remote configuration
  • Crash analysis (Crashlytics)
  • analysis

We’ll also look at some real-world examples to let you see these FlutterFire plug-ins in action.

Before we begin our tutorial, let’s break down how we will use each FlutterFire plug-in in our sample application.

We will build a virtual playground game in which a user authenticated by a certified plugin controls a character jumping on a trampoline. Jumps are synchronized to Cloud Firestore. We will use remote configuration to change the background without pushing updates to the application. Finally, we’ll use the Analytics and Crashlytics plug-ins to handle important events and crashes, respectively.

Create and configure your Firebase project

The first step is to create a project in the Firebase console and configure the local Android/iOS and Flutter applications to use the Firebase services.

To create a project in the Firebase console.

  1. Go to the Firebase console
  2. Click Add project
  3. Enter a project name and click Continue
  4. Leave Google Analytics enabled for the project and click Continue
  5. Select the Google Analytics account and click Create Project

Configure an Android app

Once the project is created, you should be able to see the dashboard of the project. You have to set up your Android project.

  1. Click on the Android icon
  2. Enter the package name and sha-1 key, then click Register Application in the Register section
  3. downloadgoogle-services.json“And put it in the Android app directory. It should look something like this.android/app/google-services.json
  4. Add Firebase dependencies as described in the Add Firebase SDK section
  5. Click to continue to the console

Configure an iOS application

Since Flutter is designed for cross-platform application development, we will also configure Flutter for native iOS apps.

  1. On the project dashboard, click the Add Application button
  2. Click on the iOS icon
  3. Enter the ID of the bundle and click Register application in the Register section
  4. Open Up Xcode and downloadGoogleService-Info.plist File and drag it to RunnerIn subfolders
  5. Follow the instructions in the “Add Firebase SDK” and “Add Initialization Code” sections
  6. Click to continue to the console

Set up a Flutter project

To use any Firebase service, the most important plug-in you need to install first is Firebase_core, which enables applications to communicate with Firebase.

"> < span style =" font-size: 14px; line-height: 20pxCopy the code

To add firebase_core dependencies, as shown in the image above, enter the pub get command in the pubspec.yaml file.

flutter pub get

Copy the code

certification

Authentication is a very important feature for any mobile application. Users may upload personal and potentially sensitive information to your application, so being able to verify a user’s identity is Paramount.

Firebase authentication provides background services and an easy to use SDK to authenticate users of your application. It supports authentication using passwords, phone numbers, and third-party platforms like Google, Facebook, Twitter, GitHub, and Apple. We will use the Firebase_auth plug-in to implement authentication in our application.

Enable authentication on the Firebase console

Before we can start integrating the Firebase_Auth plug-in in our application, we first need to enable authentication in the Firebase console.

  1. Click Authenticate from the menu on the left
  2. Select the check-in TAB
  3. Click Google, turn on the enable switch, and select support mail from the list. You can choose any login method, but for this tutorial, we will choose Google because we will implement Google login.
  4. Click next

After authentication is enabled, you will need to download Google-services. json and Googleservice-info.plist again. You can find both files, as shown below.

Add dependencies

Add Firebase_auth and Google_sign_in to pubspec.yaml, as shown below.

Firebase_core: ^1.0.1 firebase_auth: ^1.0.1 #new Google_sign_in: ^5.0.0 #newCopy the code

Code to implement authentication

Initialize the Firebase service at the beginning of the application, like this.

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

Copy the code

Add a way to log in via Google.

static Future<User? > signInWithGoogle() async { FirebaseAuth _auth = FirebaseAuth.instance; try { UserCredential userCredential; if (kIsWeb) { var googleProvider = GoogleAuthProvider(); userCredential = await _auth.signInWithPopup(googleProvider); } else { final GoogleSignInAccount googleUser = (await GoogleSignIn().signIn())! ; final GoogleSignInAuthentication googleAuth = await googleUser.authentication; final googleAuthCredential = GoogleAuthProvider.credential( accessToken: googleAuth.accessToken, idToken: googleAuth.idToken, ); userCredential = await _auth.signInWithCredential(googleAuthCredential); } final user = userCredential.user; return user; } catch (e) { print(e); }}Copy the code

We also need to set up a checkout method.

static Future<void> signOut({required BuildContext context}) async {
  final GoogleSignIn googleSignIn = GoogleSignIn();

  try {
    if (!kIsWeb) {
      await googleSignIn.signOut();
    }
    await FirebaseAuth.instance.signOut();
  } catch (e) {
    print(e);
  }
}

Copy the code

How it all works together.

Cloud Firestore

Cloud Firestore is a flexible, scalable NoSQL Cloud database that stores and synchronizes data in real time. The Cloud_firestore plug-in provides real-time listener and offline support for mobile and web. It works well in all situations, regardless of your Internet connection. It is also known as the Firestore database.

Create a database in the Firebase console for our project.

  1. Click on the Firestore database ** in the left menu.
  2. Click the Create database button
  3. To get started, select the option to start in test mode
  4. Click on the enable

Set the rules for accessing the database

We don’t want to leave the database open, so let’s restrict access to the database by setting the following rule so that only authenticated users can access it.

Rules_version = '2'. service cloud.firestore { match /databases/{database}/documents { match /{document=**} { allow read, write: if request.auth ! = null; }}}Copy the code

Add dependencies

Add cloude_FireStore dependencies as shown in the following figure: Add and dependencies in pubspec.yaml as shown in the following figure.

Firebase_auth: ^1.0.1 Google_sign_in: # ^ 5.0.0 cloud_firestore: ^ 2.2.0 newCopy the code

The implementation of the code

In the demo application, once the user logs in, we store the user’s data in the Cloud Firestore, as shown below.

User? user = await Authentication.signInWithGoogle(); if (user ! = null) { database.storeUserData(user: user); Navigator.of(context).pushReplacement( MaterialPageRoute( builder: (context) => Home( user: user, ), ), ); } //---------------------------------------------------- storeUserData({required User user}) async { AppUser appUser = AppUser(uid: user.uid, name: user.displayName, jumps: 0); await userCollection .doc(user.uid) .set(appUser.toJson()) .then((value) => print("User Added")) .catchError((error) => print("Failed to add user: $error")); }Copy the code

We will use the following method to store and synchronize the number of jumps for the logged-in user to the Firestore database.

ElevatedButton(
  style: ElevatedButton.styleFrom(primary: Colors.red),
  onPressed: () async {
    _jumpCount++;
    _datebase.updateJumpCount(
        user: _user, jumpCount: _jumpCount);
  },
  child: Text(
    'Jump',
    style: TextStyle(fontSize: 34),
  ),
),
//---------------
updateJumpCount({required User user, required int jumpCount}) async {
  await userCollection
      .doc(user.uid)
      .update({'jumps': jumpCount})
      .then((value) => print("User Added"))
      .catchError((error) => print("Failed to add user: $error"));
}

Copy the code

Now let’s add code to display the number of jumps on the dashboard using a live listener.

Container(width: 200, height: 100, decoration: BoxDecoration(color: color.grey.withopacity (0.5), border: Border.all(width: 1, color: Colors.black)), child: StreamBuilder<QuerySnapshot>( stream: _usersStream, builder: (BuildContext context, AsyncSnapshot<QuerySnapshot> snapshot) { if (snapshot.hasError) { return Text('Something went wrong'); } if (snapshot.connectionState == ConnectionState.waiting) { return Text("Loading"); } return Expanded( child: new ListView( children: snapshot.data! .docs .map((DocumentSnapshot document) { return Text( '${(document.data() as Map)['name']} : ${(document.data() as Map)['jumps']}', style: TextStyle(fontSize: 18, color: Colors.black), ); }).toList(), ), ); },),)Copy the code

As you can see, the hop count is updated in the Firestore database and displayed in real time on the dashboard.

Remote configuration

The Remote configuration plugin allows you to instantly change the behavior and appearance of your mobile application. This means you can change almost anything inside your app without releasing a new app update.

Initially, the application will read the default values from the remote configuration available in the application. Later, when needed, it can fetch new values from the remote configuration. You can control what changes need to be made, and those changes apply to all or a select group of users.

Set remote configuration values on the Firebase console

In our demo application, we will use remote configuration to control the background. Here are the steps to set these values.

  1. On the project dashboard, scroll down and select Remote Configuration
  2. Add the key as background and the value as Mountain to load the mountain background when the application opens.
  3. Click twice to publish the changes

Add dependencies

Add the Firebase_remote_config dependency as follows: pubspec.yaml.

Firebase_auth: ^1.0.1 Google_sign_in: ^5.0.0 cloud_firestore: ^2.2.0 Firebase_remote_config: ^0.10.0+2 #newCopy the code

Get the remote configuration value in the code

Now let’s write some code to set up Remote Config in the application. The code below also sets the default values so that the application can read and behave when it is first started.

Future<RemoteConfig> setupRemoteConfig() async {
  await Firebase.initializeApp();
  final RemoteConfig remoteConfig = RemoteConfig.instance;
  await remoteConfig.setConfigSettings(RemoteConfigSettings(
    fetchTimeout: const Duration(seconds: 10),
    minimumFetchInterval: Duration.zero,
  ));
  await remoteConfig
      .setDefaults(<String, dynamic>{'background': 'mountains'});
  RemoteConfigValue(null, ValueSource.valueStatic);
  return remoteConfig;
}

Copy the code

Add the following code to get and load the new values for the key background. The UI will reflect that accordingly.

FutureBuilder<RemoteConfig>( future: _datebase.setupRemoteConfig(), builder: (BuildContext context, AsyncSnapshot<RemoteConfig> snapshot) { if (snapshot.hasData) { _fetchLatestRemoteConfig(snapshot.requireData); return Image.asset( snapshot.requireData.getString('background') == 'mountains' ? 'assets/images/green_background.png' : 'assets/images/beach.png', fit: BoxFit.fill, ); } else { return Image.asset( 'assets/images/green_background.png', fit: BoxFit.fill, ); }}),Copy the code

As you can see in the image above, this changes the background from a mountain to a beach, and also changes the background of the image in the app when it restarts.

Collapse analysis

When developing a mobile app, you can’t catch all the bugs, and that’s where crash monitoring comes in. The Crashlytics plugin helps you catch fatal errors in real time.

Enable Crashlytics on the Firebase console

From the menu on the left, click Crashlytics and then click the Enable button.

Adding dependencies

Add Firebase_crashlytics add dependencies in pubspec.yaml, as shown in the figure below.

Firebase_auth: ^1.0.1 Google_sign_in: ^5.0.0 cloud_firestore: ^2.2.0 Firebase_remote_config: ^0.10.0+2 Firebase_crashlytics: ^2.0.6 #newCopy the code

Add code to catch errors

Below is the code to initialize Crashlytics and catch any uncaught errors.

//Crashlytics
await FirebaseCrashlytics.instance.setCrashlyticsCollectionEnabled(true);
// Pass all uncaught errors to Crashlytics.
Function originalOnError = FlutterError.onError as Function;
FlutterError.onError = (FlutterErrorDetails errorDetails) async {
  await FirebaseCrashlytics.instance.recordFlutterError(errorDetails);
  // Forward to original handler.
  originalOnError(errorDetails);
};

Copy the code

You can test fetching errors by simply writing the following code anywhere.

//Force crash
FirebaseCrashlytics.instance.crash();

Copy the code

In your Firebase console, it will look something like this.

Analysis of the

Analytics plug-ins can help you discover exactly how users are using your app and provide data that you can use to improve the user experience. The plug-in provides unlimited reporting for up to 500 different events.

We have chosen to enable analytics for our demo application, so we will start integrating in our application.

Add dependencies

Add Firebase_anlytics add dependencies in pubspec.yaml, as shown in the figure below.

Firebase_auth: ^1.0.1 Google_sign_in: ^5.0.0 cloud_firestore: ^2.2.0 Firebase_remote_config: ^0.10.0+2 Firebase_crashlytics: ^2.0.6 Firebase_analytics: # ^ 8.1.2 newCopy the code

Record events

There are many predefined events that can be logged, such as purchase, add to cart, login, and so on. For our example, let’s try adding a login event.

ElevatedButton( onPressed: () async { User? user = await Authentication.signInWithGoogle(); if (user ! = null) { database.storeUserData(user: user); Navigator.of(context).pushReplacement( MaterialPageRoute( builder: (context) => Home( user: user, ), ), ); await analytics.logLogin(); } }, child: Text('Sign in with Google'), )Copy the code

You can also log custom events like this.

Future<void> _testSetCurrentScreen() async {
  await analytics.setCurrentScreen(
    screenName: 'Analytics Demo',
    screenClassOverride: 'AnalyticsDemo',
  );
}

Copy the code

Here’s how you can see all the recorded events.

The full source code can be found on GitHub.

conclusion

In this tutorial, we learned how to integrate FlutterFire Authentication, Cloud Firestore, Remote Config, Crashlytics and Analytics into the Flutter application. We then built a sample application to show how these FlutterFire plug-ins would work together in a real-world application. Finally, we demonstrated how to use the FlutterFire plugin to test your application for bugs and collect data to help you improve your user experience.

The postAdd Firebase to your Flutter app with FlutterFire pluginsappeared first onLogRocket Blog.