📖

【Flutter】FCMを使ってメッセージを受信してみた時のコード(個人の備忘録)2021/10/03

2021/10/03に公開

まずは初期設定。

こちらを参考にした。
https://zuma-lab.com/posts/flutter-fcm-push-notify-settings


1番トップに書いたコード(上流に書かないとエラーになる)


final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
    FlutterLocalNotificationsPlugin();

Future<void> main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();

  FirebaseMessaging messaging = FirebaseMessaging.instance;

  ///プッシュ通知の許可
  NotificationSettings settings = await messaging.requestPermission(
    ///画面にプッシュ通知を表示する↓
    alert: true,
    announcement: false,

    ///アプリアイコンにバッジをつける
    badge: true,
    carPlay: false,
    criticalAlert: false,
    provisional: false,

    ///音を鳴らす
    sound: true,
  );

  if (settings.authorizationStatus == AuthorizationStatus.authorized) {
    print('User granted permission');
  } else if (settings.authorizationStatus == AuthorizationStatus.provisional) {
    print('User granted provisional permission');
  } else {
    print('User declined or has not accepted permission');
  }

  print('User granted permission: ${settings.authorizationStatus}');

  Future<void> firebaseMessagingBackgroundHandler(RemoteMessage message) async {
    print("バックグラウンドでメッセージを受け取りました");
  }

  FirebaseMessaging.onBackgroundMessage(firebaseMessagingBackgroundHandler);
  runApp(MyApp());
}

MyAppに書いたコード

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider<LoginKeepModel>(
      create: (_) => LoginKeepModel()..getLoginUser(),
      child: Consumer<LoginKeepModel>(builder: (context, model, snapshot) {
        model.messageState();
        if (model.isLoading) {
          return Center(child: CircularProgressIndicator());
        }
        if (model.currentUser == null) {
          return MaterialApp(
            title: '里山Asset',
            theme: ThemeData(),

            home: LoginPage(''),

            localizationsDelegates: [
              GlobalWidgetsLocalizations.delegate,
              GlobalMaterialLocalizations.delegate,
              GlobalCupertinoLocalizations.delegate,
            ],

            // localeに英語と日本語を登録する
            supportedLocales: [
              Locale("ja"),
            ],

            // アプリのlocaleを日本語に変更する
            locale: Locale('ja', 'JP'),
          );
        } else if (model.userId == null) {
          return MaterialApp(
            title: 'Flutter Demo',
            theme: ThemeData(),

            home: AgriHomePage(0),

            localizationsDelegates: [
              GlobalWidgetsLocalizations.delegate,
              GlobalMaterialLocalizations.delegate,
              GlobalCupertinoLocalizations.delegate,
            ],

            // localeに英語と日本語を登録する
            supportedLocales: [
              Locale("ja"),
            ],

            // アプリのlocaleを日本語に変更する
            locale: Locale('ja', 'JP'),
          );
        } else {
          return MaterialApp(
            title: 'Flutter Demo',
            theme: ThemeData(),

            home: HomePage(0),

            localizationsDelegates: [
              GlobalWidgetsLocalizations.delegate,
              GlobalMaterialLocalizations.delegate,
              GlobalCupertinoLocalizations.delegate,
            ],

            // localeに英語と日本語を登録する
            supportedLocales: [
              Locale("ja"),
            ],

            // アプリのlocaleを日本語に変更する
            locale: Locale('ja', 'JP'),
          );
        }
      }),
    );
  }
}

Modelに書いたコード

  void messageState() {
    _firebaseMessaging.getToken().then((token) {
      print("$token");
    });

    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      print("フォアグラウンドでメッセージを受け取りました");
      RemoteNotification? notification = message.notification;
      AndroidNotification? android = message.notification?.android;

      if (notification != null && android != null) {
        flutterLocalNotificationsPlugin.show(
            notification.hashCode,
            notification.title,
            notification.body,
            NotificationDetails(
              android: AndroidNotificationDetails(
                channel.id,
                channel.name,
                channel.description,
                icon: 'launch_background',
              ),
            ));
      }
    });
  }

Discussion