Skip to main content

Flutter Firebase Instance ID Examples

Flutter Firebase Instance ID - Step by Step Tutorial

Introduction

Firebase Instance ID is a service provided by Firebase Cloud Messaging (FCM) that generates a unique identifier for each instance of your app. This identifier is used to target specific devices for sending push notifications. In this tutorial, we will learn how to integrate Firebase Instance ID into a Flutter app.

Prerequisites

To follow along with this tutorial, make sure you have the following installed:

  • Flutter SDK
  • Android Studio (for Android development)
  • Xcode (for iOS development)
  • Firebase account

Step 1: Create a Firebase Project

  1. Go to the Firebase Console and sign in with your Google account.
  2. Click on the "Add project" button and provide a name for your project.
  3. Follow the on-screen instructions to create a new Firebase project.

Step 2: Add Firebase to Your Flutter Project

  1. Open your Flutter project in Android Studio or any other IDE of your choice.
  2. Open the pubspec.yaml file and add the following dependencies:
dependencies:
flutter:
sdk: flutter
firebase_core: ^1.0.3
firebase_messaging: ^10.0.8
  1. Save the file and run flutter pub get to fetch the new dependencies.

Step 3: Configure Firebase in Your Flutter Project

  1. Go back to the Firebase Console and select your project.
  2. Click on the "Add app" button and choose the appropriate platform (Android or iOS).
  3. Follow the on-screen instructions to register your app.
  4. Download the google-services.json file (for Android) or GoogleService-Info.plist file (for iOS).
  5. Place the downloaded file in the respective directories of your Flutter project:
  • For Android: <project>/android/app/google-services.json
  • For iOS: <project>/ios/Runner/GoogleService-Info.plist
  1. Open the android/build.gradle file and add the following code inside the buildscript section:
dependencies {
// ...
classpath 'com.google.gms:google-services:4.3.10'
}
  1. Open the android/app/build.gradle file and add the following code at the bottom:
apply plugin: 'com.google.gms.google-services'
  1. For iOS, open the ios/Podfile file and add the following line:
pod 'Firebase/Messaging'
  1. Run flutter pub get to fetch the new dependencies.

Step 4: Initialize Firebase in Your Flutter App

  1. Open the lib/main.dart file and import the necessary packages:
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
  1. Add the following code inside the main function to initialize Firebase:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
  1. Create a new class MyApp that extends StatelessWidget and add the necessary boilerplate code.

  2. Run your Flutter app to verify that Firebase has been successfully initialized.

Step 5: Get the Instance ID

  1. Inside the MyApp class, add the following code to get the Instance ID:
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;

void _getToken() async {
String? token = await _firebaseMessaging.getToken();
print('Instance ID: $token');
}
  1. Call the _getToken() method inside the build method of your MyApp class.

  2. Run your app and check the console output for the Instance ID.

Example 1: Display the Instance ID on the Screen

  1. Modify the MyApp class to include a Text widget that displays the Instance ID:
class MyApp extends StatelessWidget {
final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;


Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Firebase Instance ID'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
ElevatedButton(
onPressed: _getToken,
child: Text('Get Instance ID'),
),
StreamBuilder<String?>(
stream: _firebaseMessaging.onTokenRefresh,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Text('Instance ID: ${snapshot.data}');
} else if (snapshot.hasError) {
return Text('Error: ${snapshot.error}');
} else {
return Text('Loading...');
}
},
),
],
),
),
),
);
}

// ...
}
  1. Run your app and click the "Get Instance ID" button to display the Instance ID on the screen.

Example 2: Send Push Notification to a Specific Device

  1. Go to the Firebase Console and select your project.
  2. Click on the "Cloud Messaging" tab.
  3. Click on the "New notification" button.
  4. Enter the Instance ID of the device you want to send the notification to.
  5. Customize the notification message and click "Send test message".

Conclusion

In this tutorial, we have learned how to integrate Firebase Instance ID into a Flutter app. We covered the installation process, initializing Firebase, getting the Instance ID, and displaying it on the screen. We also demonstrated how to send a push notification to a specific device using the Instance ID. Firebase Instance ID is a powerful tool for targeting specific devices and delivering personalized notifications to your app users.