---
# System prepended metadata

title: Flutter Notification
tags: [work, flutter]

---

# Flutter Notification

###### tags: `work` `flutter`

### Android
- Tạo android app trên firebase với package name và SHA-1 tương ứng với app.
- Add file google-services.json vào project.
- Modify build.gradle file

##### Project-level build.gradle
```
buildscript {
  repositories {
    // Check that you have the following line (if not, add it):
    google()  // Google's Maven repository
  }
  dependencies {
    ...
    // Add this line
    classpath 'com.google.gms:google-services:4.3.5'
  }
}

allprojects {
  ...
  repositories {
    // Check that you have the following line (if not, add it):
    google()  // Google's Maven repository
    ...
  }
}
```

##### App-level build.gradle
```
apply plugin: 'com.android.application'
// Add this line
apply plugin: 'com.google.gms.google-services'

dependencies {
  // Import the Firebase BoM
  implementation platform('com.google.firebase:firebase-bom:26.5.0')

  // Add the dependency for the Firebase SDK for Google Analytics
  // When using the BoM, don't specify versions in Firebase dependencies
  implementation 'com.google.firebase:firebase-analytics-ktx'
  implementation 'com.google.firebase:firebase-messaging:21.0.1'

  // Add the dependencies for any other desired Firebase products
  // https://firebase.google.com/docs/android/setup#available-libraries
}
```

- Set name property of application in AndroidManifest.xml (```<app-name>/android/app/src/main/```).
```
<application android:name=".Application">
```
- (Option, but recommended) add ```intent-filter``` within the ```<activity>``` tag of ```android/app/src/main/AndroidManifest.xml``` file.
```
  <intent-filter>
      <action android:name="FLUTTER_NOTIFICATION_CLICK" />
      <category android:name="android.intent.category.DEFAULT" />
  </intent-filter>
```
- Add `Application.kt` trong cùng thư mục với `MainActivity.kt` (`<app-name>/android/app/src/main/java/<app-organization-path>/`).
```
package vn.com.fsoft.gst_notification

import io.flutter.app.FlutterApplication
import io.flutter.plugin.common.PluginRegistry
import io.flutter.plugins.firebase.messaging.FlutterFirebaseMessagingBackgroundService
import io.flutter.plugins.firebase.messaging.FlutterFirebaseMessagingPlugin
import com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin
import io.flutter.Log

import io.flutter.plugin.common.PluginRegistry.PluginRegistrantCallback


class Application : FlutterApplication(), PluginRegistrantCallback {
    override fun onCreate() {
        super.onCreate()
    }

    override fun registerWith(registry: PluginRegistry) {
        if (registry != null) {
            FlutterLocalNotificationPluginRegistrant.registerWith(registry);
        }
    }
}


class FlutterLocalNotificationPluginRegistrant {

    companion object {
        fun registerWith(registry: PluginRegistry) {
            if (alreadyRegisteredWith(registry)) {
                Log.d("Local Plugin", "Already Registered");
                return
            }
            FlutterLocalNotificationsPlugin.registerWith(registry.registrarFor("com.dexterous.flutterlocalnotifications.FlutterLocalNotificationsPlugin"))
            Log.d("Local Plugin", "Registered");
        }

        private fun alreadyRegisteredWith(registry: PluginRegistry): Boolean {
            val key = FlutterLocalNotificationPluginRegistrant::class.java.canonicalName
            if (registry.hasPlugin(key)) {
                return true
            }
            registry.registrarFor(key)
            return false
        }
    }
}
```

### IOS

- Tạo project iOS trên firebase với bundleId tương ứng
- Tạo APNs certificate firebase messaging
- Add file GoogleService-Info.plist vào project iOS
- Add Capabilities
    - Background Modes: 
        - Background fetch
        - Remote notification
    - Push notifications

### Payload message
##### Android
* Không được có filed `notification`.
```
{
    "to" : "[fcm device token]",
    "priority" : "high",
    "content-available" : 1,
    "data" : {
    	"title" : "Title of message",
    	"body" : "Content of message",
        "key1" : "value1",
        "key2" : "value2"
    }
}
```
##### iOS
* Bắt buộc phải có filed `notification`.
```
{
    "to":"[fcm device token]",
    "notification" : {
    	"title":"Title of message",
    	"body":"Content of message",
    	"sound":"default"
    },
    "priority" : "high",
    "content-available" : 1,
    "data" : {
    	"title" : "Title of message",
    	"body" : "Content of message",
        "key1" : "value1",
        "key2" : "value2"
    }
}
```
### Sử dụng

- Đảm bảo init trước khi dùng:
`await FirebaseNotification.initialize();`
- Lấy fcm device token (dùng để gửi cho server):
`final token = await FirebaseNotification.instance.getToken();`
- Delete token (khi sign out hoặc hết session, gửi lên server để clear token):
`FirebaseNotification.instance.deleteToken();`
- Get Initial Message khi open app từ Terminated mode, (và Background mode)
`final message = await FirebaseNotification.instance.getInitialMessage();`
- Listen Stream khi có message và mở message ở Foreground Mode
`FirebaseNotification.onMessage.listen((String data) { // todo });`
`FirebaseNotification.onMessageOpenedApp.listen((String data) { // todo });`

---
#### [`Gái xinh ở đây`](https://firebase.flutter.dev/)