FCM 1 : firebase_messaging setting

2025. 12. 18. 13:59
반응형

FCM(Firebase Cloud Messaging)을 이용해서 Notifications을 설정해보려고 한다. 가장 먼저 Firebase_messaging 패키지 설정하는 내용을 정리해보겠다.

 

초기 설정방법은 아래의 유튜브를 참고해서 진행했다.

Push Notifications in Flutter using FCM with REST API - HTTP V1 API - Firebase Cloud Messaging

 

1. Firebase_messaging package Install

가장먼저 해줄것은 패키지를 설치하는 것이다. 

flutter pub add firebase_messaging

 

2. Firebase Messaging setting

Firebase Messaging을 이용한 Notifications 설정을 해준다.

코드 전체 예시

import 'package:firebase_messaging/firebase_messaging.dart';

class NotificationService {

  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;

  initFCM() async {
    await _firebaseMessaging.requestPermission();

    final fcmToken = await _firebaseMessaging.getToken();
    print("FCM Token: $fcmToken");

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

    await _firebaseMessaging.subscribeToTopic('allUsers');

    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      print('Received a message while in the foreground!');
      print('Message data: ${message.data}');

      if (message.notification != null) {
        print('Message also contained a notification: ${message.notification?.title} - ${message.notification?.body}');
      }
    });

    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      print('Message: ${message.notification?.title}');
    });
  }

}

위의 코드는 유튜브를 참고하면서 설정한 파일 코드이다.

토큰 확인

final fcmToken = await _firebaseMessaging.getToken();
print("FCM Token: $fcmToken");

이 부분은 메세지를 보낼때 필요한 사용자의 FCM토큰을 발급해서 확인하기 위해서 사용했다. TEST로 알림을 보낼때 사용했다.

권한

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

여기는 알림, 사운드, 배지알림의 권한을 설정해주는 부분이다. 모두 true로 되어있어야 실행이 되기때문에 우선은 모두 true로 설정해주었다. 나중에 알림 설정에 대한 권한을 앱 설정으로 따로 다룰때 이 부분을 이용하면 될것같다.

앱 상태에 따른 알림 설정

FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      print('Received a message while in the foreground!');
      print('Message data: ${message.data}');

      if (message.notification != null) {
        print('Message also contained a notification: ${message.notification?.title} - ${message.notification?.body}');
      }
    });

    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      print('Message: ${message.notification?.title}');
    });
  }

onMessage, OnMessageOpenedApp 지금 코드에는 두가지가 있습니다. 각각의 앱의 상태에 따라 알림을 어떻게 할것인지를 정의하는 메소드입니다. onMessage는 포그라운드 상태 즉 앱이 실행되고 있을때의 상태에서 처리방법을 정의합니다. OnMessageOpenedApp은 포그라운드 상태일경우 알림을 터치했을때 앱의 특정 동작을 하도록 정의합니다.

3. main() 설정

Future<void> handlerFirebaseBackgroundMessage(RemoteMessage message) async {
  print('Handling a background message: ${message.messageId}');
}


void main() async {
  //firebase 초기화
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);

  final notificationService = NotificationService();
  await notificationService.initFCM();
  FirebaseMessaging.onBackgroundMessage(handlerFirebaseBackgroundMessage);

  runApp(ProviderScope(child: MyApp()));
}

main() 안에 notifications에 대한 설정을 아래와 같이 해줍니다.

final notificationService = NotificationService();
await notificationService.initFCM();
FirebaseMessaging.onBackgroundMessage(handlerFirebaseBackgroundMessage);

handlerFirebaseBackgroundMessage는 main() 외부에 따로 정의를 해줍니다.

Future<void> handlerFirebaseBackgroundMessage(RemoteMessage message) async {
  print('Handling a background message: ${message.messageId}');
}

이때 onBackgroundMessage는 앱이 백그라운드 혹은 종료의 상태일때 알림을 띄울 수 있게 해줍니다. 그리고 여기서 수신한 알림을 터치했을때는 위의 onMessageOpendeApp의 행동으로 연결됩니다.

 

4. Notification Test

그럼 제대로 설정이 제대로 되었는지 확인해보겠습니다.

우선 firebase console에서 messaging으로 들어가서 알림 메시지를 선택합니다.

 

그러면 아래의 화면이 나오게 됩니다.

저기서 알림 제목, 알림 텍스트를 입력하고, 테스트 메시지 전송을 선택합니다. fcm token을 입력하라는 창이 나오게 됩니다.

NotificationService 클래스에 아래의 코드가 입력되어있으면 fcm 토큰을 받을 수 있습니다. 그러면 그 토큰을 입력해주세요.
final fcmToken = await _firebaseMessaging.getToken();
    print("FCM Token: $fcmToken");

그리고 나서 앱을 백그라운드 상태로 만든상태에서  테스트 버튼을 눌러서 알림을 보내게 되면 백그라운드 상태에서의 notification이 되는 것을 확인할 수 있습니다.

이렇게 간단하게 FCM을 통해서 notification을 전송하는 과정을 정리해보았습니다.

이렇게 Firebase Console을 이용해서 알림을 보낼 수 있지만 과정이 복잡하기도 하고 결국 일반 사용자가 알림을 보내기 위해서는 보안 문제와 번거러움이 발생하게 됩니다. 그래서 Notification과정을 자동화하고 console이 아닌 앱에서 보내게 하기 위해서는 Functions를 이용해야합니다. 다음글에서는 Functions를 이용한 과정을 정리해보겠습니다.

Notification 기능을 완성하기 위해서 FCM, Functions 등 처음 해보는 기능들을 도전해보고 있지만 천천히 해보다 보면 결국 어렵지 않게 할 수 있다는 것을 깨달을 수 있습니다.

반응형

'Flutter > 성당 앱' 카테고리의 다른 글

FCM 2: Functions 설정 그리고 오류  (0) 2025.12.31

BELATED ARTICLES

more