Flutter + Firebase Messaging: A Match Made in App Heaven for Newbie Developers!
Tags: flutter, dart, firebase, messaging
Published: 2023-05-05 07:33:24



Welcome, dear novice app developer! If you're looking to add some pizzazz to your Flutter app with real-time notifications, you're in the right place! We'll show you how to set up Firebase Messaging in your Flutter app with ease. So, buckle up and let's get this party started! 🎉

### What's Firebase Messaging, you ask?

Firebase Cloud Messaging (FCM) is a free messaging service provided by Google that allows you to send notifications and data messages to your users' devices. It's the perfect solution for adding real-time communication to your app without breaking a sweat! 💪

### Step 1: Set Up Firebase in Your Flutter Project

Before diving into code, you'll need to create a Firebase project and connect it with your Flutter app. Follow the [official FlutterFire documentation](https://firebase.flutter.dev/docs/overview) for step-by-step instructions.

### Step 2: Add Firebase Messaging Dependency

Add the `firebase_messaging` package to your `pubspec.yaml` file:

```yaml
dependencies:
  flutter:
    sdk: flutter
  firebase_messaging: ^11.0.0
```

Then, run `flutter pub get` to install the package.

### Step 3: Configure Firebase Messaging

In your `main.dart`, import the required packages and initialize Firebase:

```dart
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';

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

### Step 4: Request Permission for Notifications

Add the following code snippet inside your `MyApp` widget's `build` method to request notification permission:

```dart
FirebaseMessaging.instance.requestPermission(
  alert: true,
  badge: true,
  sound: true,
);
```

### Step 5: Register Device Token

You'll need a unique device token to send notifications to a specific device. To obtain it, add the following code snippet in your `main` function:

```dart
void main() async {
  // ... existing code
  FirebaseMessaging.onBackgroundMessage(_backgroundMessageHandler);
  FirebaseMessaging.instance.getToken().then((token) {
    print('Device Token: $token');
  });
  runApp(MyApp());
}

Future<void> _backgroundMessageHandler(RemoteMessage message) async {
  print('A background message arrived: ${message.messageId}');
}
```

Save the printed token. You'll use it to send notifications via FCM.

### Step 6: Handle Incoming Notifications

Let's handle notifications when the app is in the foreground:

```dart
FirebaseMessaging.onMessage.listen((RemoteMessage message) {
  print('A foreground message arrived: ${message.messageId}');
  // You can add custom logic here, like displaying a snackbar or dialog.
});
```

Voilà! 🎉 Your app is now set up to receive notifications from FCM!

### Sending Test Notifications

To test your shiny new notification system, use the following cURL command, replacing `<YOUR-FCM-SERVER-KEY>` with your FCM server key and `<YOUR-DEVICE-TOKEN>` with the printed device token:

```
curl -X POST \
  https://fcm.googleapis.com/fcm/send \
  -H 'Authorization: key=<YOUR-FCM-SERVER-KEY>' \
  -H 'Content-Type: application/json' \
  -d '{
        "to": "<YOUR-DEVICE-TOKEN>",
        "notification": {
          "title": "Test Notification",
          "body": "This is a test notification from FCM"
        }
     }'

```