【Flutter】とにかくFCMを実装したい人(Push通知)

Flutter

備忘録です。

FCMとは

Firebase Cloud Messaging (FCM) は、サーバーからデバイスにプッシュ通知を送信できる無料のクロスプラットフォーム サービスです。FCM を使用すると、Android、iOS、Web アプリにメッセージを送信できます。FCM は、メッセージを確実かつバッテリー効率的に配信できます。

実装方法

firebaseプロジェクトの作成

  1. Firebase コンソールにアクセスします。
  2. [新規プロジェクトを作成] をクリックします。
  3. プロジェクトの名前と地域を選択します。
  4. [作成] をクリックします。
  5. プロジェクトが作成されたら、[開始] をクリックします。
  6. アプリの詳細を入力します。
  7. [登録] をクリックします。

firebase_coreとfirebase_messagingの追加

firebase_core | Flutter package
Flutter plugin for Firebase Core, enabling connecting to multiple Firebase apps.
firebase_messaging install | Flutter package
Flutter plugin for Firebase Cloud Messaging, a cross-platform messaging solution that lets you reliably deliver messages...

flutterプロジェクトとfirebaseの紐付け

Flutter アプリに Firebase を追加する

初期化・呼び出し方法

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  // firebase_optionsの設定オプションを渡す
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  runApp(
    const MyApp(),
  );
}

通知取得方法

Future<void> generateNoticeSetting() async {
  final messaging = FirebaseMessaging.instance;
  final settings = await messaging.requestPermission();
  debugPrint(' User granted permission: ${settings.authorizationStatus}');

  try {
    final token = await messaging.getToken();
    debugPrint('🔥 FCM TOKEN: $token');
  } on Exception catch (e) {
    debugPrint('デバイストークンの取得エラー: $e');
  }

  FirebaseMessaging.onMessage.listen((RemoteMessage message) {
    debugPrint('Got a message in the foreground!');

    if (message.notification != null) {
      debugPrint('ForegroundMessage Title: ${message.notification?.title}');
      debugPrint('ForegroundMessage Body: ${message.notification?.body}');
    }
  });
  FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
    // 通知をタップしてアプリを開いた場合、ここで通知を処理する
    if (message.notification != null) {
      debugPrint('ForegroundMessage Title: ${message.notification?.title}');
      debugPrint('ForegroundMessage Body: ${message.notification?.body}');
    }
  });

  await FirebaseMessaging.instance.getInitialMessage().then((message) {
    if (message != null) {
      debugPrint('ForegroundMessage Title: ${message.notification?.title}');
      debugPrint('ForegroundMessage Body: ${message.notification?.body}');
    }
  });
}

通知が来ない時に見直すこと

証明書

証明書まわりに慣れていないとやりづらいと思います。俺は全て以下で統一しています。(appleはp12を推奨しているようです。)

Sign In - Apple
Sign in with your Apple ID

許諾

push通知を許可する許諾を出していますか?権限が足りていないとうまくいきません。

firebaseに登録していない

firebaseプロジェクト>プロジェクトの設定>cloud messaging>Appleアプリの構成に(p8の開発・本番証明書)or(p12)が登録されているか確認してください。

pushは来ているけど開いた時の処理がうまくいかない人

私の場合、ScaffoldWidgetが無い時に失敗することが多かったです。

アプリの画面を生成する前のcontextを使ったりしている可能性があるので、ScaffoldWidgetを返すときに上記のpush通知を受け取った時の処理を書いてみてください。

Buy me a coffee!

Flutterアプリ開発
シェアする
sogaをフォローする
タイトルとURLをコピーしました