Firebase & Crashlytics in Flutter and Swift

filip-v.png
Filip Varda 12 min read
1-130.jpg

What is Firebase?

In short, Firebase is Google’s mobile application development platform that helps you build, improve, and grow your app. More specific Firebase is a toolset that allows a developer to cover a large portion of the services that the developer should normally build by himself. Those services include things like analytics, authentication, databases, configuration, file storage, push messaging, etc.

All of those services are hosted in the cloud and scale from little to no effort on the developer part, meaning that products have backend components that are fully maintained and operated by Google. Client SDKs provided by Firebase interact with those backend services directly, with no need to establish any middleware between your app and the service. So, if you’re using one of the Firebase database options, you typically write code to query the database in your client app.

If you are asking yourself “What sort of apps is Firebase good for?” then the answer is that there’s no limit to the types of apps that can be helped by Firebase products. There are only limits to the platforms it can be used on. iOS and Android are the primary targets for the Firebase SDKs, and there’s increasing support for web, Flutter, Unity, and C++. You should also know there’s an Admin SDK available for a variety of languages, to be used with any backend components you might require.

What is Crashlytics?

Firebase Crashlytics is a lightweight, real-time crash reporter that helps you track, prioritize, and fix stability issues that erode your app quality. Crashlytics save you troubleshooting time by intelligently grouping crashes and highlighting the circumstances that lead up to them.

Find out if a particular crash is impacting a lot of users. Get alerts when an issue suddenly increases in severity. Figure out which lines of code are causing crashes.

Firebase Crashlytics helps you track, prioritize, and fix stability issues that erode app quality in realtime, which allows you to spend less time triaging and troubleshooting crashes and more time building app features that delight users.

Crashlytics quickly pinpoints the root cause of crashes by intelligently grouping an avalanche of crashes into a manageable list of issues. It also provides information on why a crash occurred and what happened leading up to it. With this insight, you can uncover the root cause of crashes more quickly.

Crashlytics lets you understand what issue to tackle first with prioritizing by the impact on actual users, so you know how best to triage effort for fixing bugs.

Crashlytics never miss a critical crash. You can get real-time alerts for new issues, regressed issues, and burgeoning issues that might require immediate attention, no matter where you are.

With all that being said, it’s time to take a look at how to install Firebase and use it.

Firebase in Swift

We will begin with Firebase for Swift. Here are the requirements to install Firebase:

  • Xcode 11.0 or later
  • CocoaPods 1.9.0 or later
  • Your project must target iOS 10 or later.
  • Set up a physical iOS device or use the iOS simulator to run your app.

Step 1: Create a Firebase project

After making sure that you have everything you need, we can now create a Firebase project. To do so, open the Firebase console, click Add project, then select or enter a Project name.

You are creating a new project, so you can edit the Project ID, but this is optional since Firebase automatically assigns a unique ID to your Firebase project.

After that, you can click Continue.

Step 2: Register your app with Firebase

After you have a Firebase project, you can add your iOS app to it. Go to the Firebase console.

In the center of the project overview page, click the iOS icon to launch the setup workflow.

If you’ve already added an app to your Firebase project, click Add app to display the platform options.

Enter your app’s bundle ID in the iOS bundle ID field. Make sure to enter the bundle ID that your app is actually using. The bundle ID value is case-sensitive, and it cannot be changed for this Firebase iOS app after it’s registered with your Firebase project.

This is optional, but if you like you can enter other app information: App nickname and App Store ID.

Click Register app.

Step 3: Add a Firebase configuration file

After clicking the Register app you should be able to click Download GoogleService-Info.plist to obtain your Firebase iOS config file (GoogleService-Info.plist).

Here are something that you might like to know about this config file:

  • The Firebase config file contains unique, but non-secret identifiers for your project. You can learn more about this config file by clicking this link.
  • You can download your Firebase config file again at any time.
  • Make sure the config file name is not appended with additional characters, like (2).

Move your config file into the root of your Xcode project. If prompted, select to add the config file to all targets.

Keep in mind that if you have multiple bundle IDs in your project, you must associate each bundle ID with a registered app in the Firebase console so that each app can have its own GoogleService-Info.plist fil.

Step 4: Add Firebase SDKs to your app

Firebase recommends that you install the SDK using CocoaPods. If you don’t know what CocoaPods is and you don’t have them installed I recommend that you visit this link and read through the documentation and install everything you need before you proceed with this article.

Create a Podfile if you don’t already have one:

Navigate to your project directory using terminal

cd your-project-directory

Create a pod file

pod init

Open Xcode or open the podfile with a text editor. In your Podfile, add the Firebase pods that you want to use in your app. You can add any of the supported Firebase products to your iOS app. After that close Xcode, open Terminal again, and install the pods

pod install

That’s it! You are ready to use Firebase in your Xcode project. Just make sure to open your .xcworkspace file to see the pods you just installed.

Step 5: Initialize Firebase in your app

The final step is to add initialization code to your application and this is how to do it.

Import the Firebase module in your UIApplicationDelegate.swift:

import Firebase

Configure a FirebaseApp shared instance. This is typically done in your app's application:didFinishLaunchingWithOptions: method:

FirebaseApp.configure()

If you’ve included Firebase Analytics, you can run your app to send verification to the Firebase console that you’ve successfully installed Firebase.

Firebase in Flutter

Let’s continue with Firebase for Flutter. Here are the requirements to install Firebase:

  • Install your preferred editor or IDE.
  • Make sure that your Flutter app targets iOS 8 or later.
  • Set up a physical iOS device or the iOS simulator for running your app.

For Cloud Messaging, complete the following tasks:

  • Set up a physical iOS device.
  • Obtain an Apple Push Notification Authentication Key for your Apple Developer account.
  • Enable Push Notifications in XCode under App > Capabilities.
  • For all other Firebase products, you can use either a physical iOS device or the iOS simulator.

Install Flutter for your specific operating system, including the following:

  • Flutter SDK
  • Supporting libraries
  • Platform-specific software and SDKs
  • Sign in to Firebase using your Google account.

Step 1: Create a Firebase project

Before you can add Firebase to your Flutter app, you need to create a Firebase project to connect to your app.

Create a Firebase project

In the Firebase console, click Add project, then select or enter a Project name. If you have an existing Google Cloud Platform (GCP) project, you can select the project from the dropdown menu to add Firebase resources to that project.

This part is optional but, if you are creating a new project, you can edit the Project ID. As mentioned before, Firebase automatically assigns a unique ID to your Firebase project. After Firebase provisions resources for your Firebase project, you cannot change your project ID. To use a specific identifier, you must edit your project ID during this setup step. After you are finished with that, click Continue.

Step 2: Register your app with Firebase

Before we jump into registering your app, there is one important note: If you’re releasing your Flutter app on both iOS and Android, register both the iOS and Android versions of your app with the same Firebase project.

In the center of the Firebase console’s project overview page, click the iOS icon to launch the setup workflow. If you’ve already added an app to your Firebase project, click Add app to display the platform options.

Enter your app’s bundle ID in the iOS bundle ID field. Find this bundle ID from your open project in XCode. Select the top-level app in the project navigator, then access the General tab. The Bundle Identifier value is the iOS bundle ID (for example, com.yourcompany.ios-app-name).

This step is optional but, you can enter other app information as prompted by the setup workflow, here are the explanations for both of the fields:

After you finished filling in all the info, click the Register app.

Step 3: Add a Firebase configuration file

This step is very similar to adding a Firebase configuration file to your iOS project, we just need to place the file in the right folder. To do so, click Download GoogleService-Info.plist to obtain your Firebase iOS config file (GoogleService-Info.plist) and using XCode, move the file into the Runner/Runner directory of your Flutter app.

Step 4: Add FlutterFire plugins

Before we jump into FlutterFire plugins, let's take a moment to go get a better understanding of what is FlutterFire.

Flutter uses plugins to provide access to a wide range of platform-specific services, such as Firebase APIs. Plugins include platform-specific code to access services and APIs on each platform.

Firebase is accessed through a number of different libraries, one for each Firebase product (for example: Realtime Database, Authentication, Analytics, or Storage). Flutter provides a set of Firebase plugins, which are collectively called FlutterFire.

Since Flutter is a multi-platform SDK, each FlutterFire plugin is applicable for both iOS and Android. So, if you add any FlutterFire plugin to your Flutter app, it will be used by both the iOS and Android versions of your Firebase app.

Here is a link with the up-to-date docs that you can visit for the most up-to-date list of FlutterFire plugins.

Okay, back to work, let's add Firebase to your Flutter app.

Ensure that your app is not currently running in your emulator or on your device. From the root directory of your Flutter app, open your pubspec.yaml file. Add the FlutterFire plugin for the Firebase Core Flutter SDK.

dependencies:
flutter:
sdk: flutter
# Add the dependency for the Firebase Core Flutter SDK
firebase_core: ^0.4.0+9

Add the FlutterFire plugins for the Firebase products that you want to use in your app. For example:

dependencies:
flutter:
sdk: flutter
# Check that you have this dependency (added in the previous step)
firebase_core: ^0.4.0+9

# Add the dependency for the FlutterFire plugin for Google Analytics
firebase_analytics: ^5.0.2

# Add the dependencies for any other Firebase products you want to use in your app
# For example, to use Firebase Authentication and Cloud Firestore
firebase_auth: ^0.14.0+5
cloud_firestore: ^0.12.9+5

Run flutter packages get. For more information about managing packages and plugins, refer to this link.

If you added Analytics, run your app to send verification to Firebase that you’ve successfully integrated Firebase. Otherwise, you can skip the verification step.

You’re all set! Your Flutter app is registered and configured to use Firebase.

Try out an example app with Analytics

Like all packages, the firebase_analytics plugin comes with an example program.

Open a Flutter app that you’ve already configured to use Firebase. Access the lib directory of the app, then delete the existing main.dart file.

From the Google Analytics example program repository, copy-paste the following two files into your app’s lib directory:

  • main.dart
  • tabs_page.dart

Run your Flutter app.

Go to your app’s Firebase project in the Firebase console, then click Analytics in the left-nav.

Click Dashboard. If Analytics is working properly, the dashboard shows an active user in the “Users active in the last 30 minutes” panel (this might take time to populate this panel).

Click DebugView. Enable the feature to see all the events generated by the example program.

For more information about setting up Analytics, visit the getting started guides for iOS and for Android.

Crashlytics in Swift

Since we already went through what is Crashlytics, we are going to jump right into configuring it.

Step 1: Set up Crashlytics in the Firebase console

Click Crashlytics in the left-hand nav panel of the Firebase console.

If your Firebase project has multiple apps registered in it, select the app you just added from the dropdown next to Crashlytics in the top bar of the console.

Click Enable Crashlytics.

Step 2: Add Firebase Crashlytics to your app

Open the podfile you created for your Firebase project and add the FirebaseCrashlytics pod. For an optimal experience with Firebase Crashlytics, it’s recommended to enable Google Analytics in your project by adding the Firebase pod for Analytics to your app as well. Make sure you add Google Analytics Version 6.3.1 or later in order to get real-time crash-free users and breadcrumbs.

pod 'Firebase/Crashlytics'

# Recommended: Add the Firebase pod for Google Analytics
pod 'Firebase/Analytics'

Close Xcode and install the pods using Terminal, then re-open your .xcworkspace file to see the project in Xcode.

pod install

Import the Firebase module in your UIApplicationDelegate.

import Firebase

Configure a FirebaseApp shared instance, typically in your app's application:didFinishLaunchingWithOptions: method.

FirebaseApp.configure()

Recompile your app and the build should be successful.

Step 3: Initialize Crashlytics

You can initialize Crashlytics by adding a run script to your project’s build phase. The run script allows Xcode to automatically upload your project’s dSYM file whenever your app crashes so that Crashlytics can automatically generate crash reports. Make sure your new build phase is the project’s last build phase or Crashlytics can’t initialize properly.

Open your project in Xcode, then select its project file in the left navigator.

From the Select a project or target dropdown, select your main build target.

Select the Build Phases tab, then click add > New Run Script Phase.

Expand the new Run Script section that appears. In the script field (located under the Shell field), add a new run script.

"${PODS_ROOT}/FirebaseCrashlytics/run"

Add your app’s dSYM location as an input file that enables Crashlytics to automatically generate dSYMs for large apps more quickly. For example:

${DWARF_DSYM_FOLDER_PATH}/${DWARF_DSYM_FILE_NAME}/Contents/Resources/DWARF/${TARGET_NAME}

You can also provide your app’s built Info.plist location to the build phase's Input Files field.

$(SRCROOT)/$(BUILT_PRODUCTS_DIR)/$(INFOPLIST_PATH)

After you add the SDK to your app, Crashlytics automatically gets to work listening for and collecting crash reports.

Finally, run your app. Your device logs display the Firebase verification that initialization is complete. Make sure to disconnect the simulator from the Xcode debugger to see crashes in the Firebase console.

Crashlytics in Flutter

Configuration of Crashlytics in Flutter is pretty simple.

Step1: Set up Crashlytics in the Firebase console

Click Crashlytics in the left-hand nav panel of the Firebase console.

If your Firebase project has multiple apps registered in it, select the app you just added from the dropdown next to Crashlytics in the top bar of the console.

Click Enable Crashlytics.

Step 2: Add Firebase Crashlytics to your app

Add Package Dependency in pubspec.yaml

dependencies:
flutter:
sdk: flutter
# Check that you have this dependency (added in the previous step)
firebase_core: ^0.4.0+9

# Add the dependency for the FlutterFire plugin for Google Analytics
firebase_analytics: ^5.0.2
# Add the dependency for the Crashlytics
firebase_crashlytics: "^0.2.0"

Add the following classpath to your android/build.gradle file.

dependencies {
classpath 'com.google.firebase:firebase-crashlytics-gradle:2.2.0'}

Apply the following Plugin to the end of your android/app/build.gradle file.

apply plugin: 'com.google.firebase.crashlytics'

Add the Firebase Crashlytics SDK, in your android/app/build.gradle files.

dependencies {
// Adding Firebase Crashlytics SDK
implementation 'com.google.firebase:firebase-crashlytics:17.0.0-beta01'
}

(iOS )

Select Runner at project navigation from Xcode.

Then Select the Tab Build phase => Click on + > New Run Script Phase

Add ${PODS_ROOT}/FirebaseCrashlytics/run to the Type a script.. text box.

Import package At Your Project File:

import 'package:firebase_crashlytics/firebase_crashlytics.dart';

Step 3: Initialize Crashlytics

Add Firebase Crashlytics Instance In Your Flutter App.

<strong>void </strong>main() {
  <em>// Set `enableInDevMode`to true to see reports while in debug mode
  // This is only to be used for confirming that reports are being
  // submitted as expected. It is not intended to be used for  //everyday development.  </em><strong>Crashlytics.<em>instance</em>.enableInDevMode = true;</strong>  <em>// Pass all uncaught errors to Crashlytics.
  </em>FlutterError.<em>onError </em>= Crashlytics.<em>instance</em>.recordFlutterError;
  WidgetsFlutterBinding.<em>ensureInitialized</em>();
  SystemChrome.<em>setEnabledSystemUIOverlays</em>([SystemUiOverlay.<strong>bottom</strong>]).then((_) {
    SharedPreferences.<em>getInstance</em>().then((prefs) {
      <strong>var </strong>darkModeOn = prefs.getBool(<strong>'darkMode'</strong>) ?? <strong>true</strong>;
      runZoned(() {
        runApp(ChangeNotifierProvider<ThemeNotifier>(
          create: (_) => ThemeNotifier(darkModeOn ? darkTheme : lightTheme),
          child: MyApp(),
        ));
      }, onError: Crashlytics.<em>instance</em>.recordError);
    });
  });
}

That’s it! Rebuild your app and everything should work.

$ flutter run

You will be able to see the crashlytics dashboard in the firebase console on a successful installation.

That’s all folks! If there are any more questions that you would like to get answered, I’ll leave some link to official Firebase documentation :)

Add Firebase to your iOS project

Add Firebase to your Flutter app 

Get started with Firebase Crashlytics

Crashlytics