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
- Go to the Firebase Console and sign in with your Google account.
- Click on the "Add project" button and provide a name for your project.
- Follow the on-screen instructions to create a new Firebase project.
Step 2: Add Firebase to Your Flutter Project
- Open your Flutter project in Android Studio or any other IDE of your choice.
- Open the
pubspec.yaml
file and add the following dependencies:
dependencies:
flutter:
sdk: flutter
firebase_core: ^1.0.3
firebase_messaging: ^10.0.8
- Save the file and run
flutter pub get
to fetch the new dependencies.
Step 3: Configure Firebase in Your Flutter Project
- Go back to the Firebase Console and select your project.
- Click on the "Add app" button and choose the appropriate platform (Android or iOS).
- Follow the on-screen instructions to register your app.
- Download the
google-services.json
file (for Android) orGoogleService-Info.plist
file (for iOS). - 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
- Open the
android/build.gradle
file and add the following code inside thebuildscript
section:
dependencies {
// ...
classpath 'com.google.gms:google-services:4.3.10'
}
- Open the
android/app/build.gradle
file and add the following code at the bottom:
apply plugin: 'com.google.gms.google-services'
- For iOS, open the
ios/Podfile
file and add the following line:
pod 'Firebase/Messaging'
- Run
flutter pub get
to fetch the new dependencies.
Step 4: Initialize Firebase in Your Flutter App
- 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';
- Add the following code inside the
main
function to initialize Firebase:
void main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(MyApp());
}
Create a new class
MyApp
that extendsStatelessWidget
and add the necessary boilerplate code.Run your Flutter app to verify that Firebase has been successfully initialized.
Step 5: Get the Instance ID
- 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');
}
Call the
_getToken()
method inside thebuild
method of yourMyApp
class.Run your app and check the console output for the Instance ID.
Example 1: Display the Instance ID on the Screen
- Modify the
MyApp
class to include aText
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...');
}
},
),
],
),
),
),
);
}
// ...
}
- 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
- Go to the Firebase Console and select your project.
- Click on the "Cloud Messaging" tab.
- Click on the "New notification" button.
- Enter the Instance ID of the device you want to send the notification to.
- 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.