[Flutter] Flutter FCM 세팅 (푸시 알림) - 3

soonmuu·2023년 2월 22일

flutter 푸시알림

목록 보기
3/3
post-thumbnail

참고 블로그
https://velog.io/@leedool3003/Flutter-FCM-Firebase-Cloud-Messagin-%EC%97%B0%EB%8F%99
https://bangu4.tistory.com/364

전체적인 흐름

  1. firebase 프로젝트 생성
  2. 패키지 설치
  3. android, ios 세팅
  4. flutter 코드 추가
  5. firebase에서 테스트 메시지로 알림 테스트

4. flutter 코드 추가

  1. firebase 초기화
  2. background 설정
  3. firebase setting
  4. 함수 호출
  • main.dart에 푸시를 위한 코드를 추가해준다

1. firebase 초기화

import 'package:flutter/foundation.dart'
    show kIsWeb;
    
void main() async {
  // WidgetsFlutterBinding 인스턴스 초기화
  WidgetsFlutterBinding.ensureInitialized();

// firebase 초기화
// 각 key 값은 google-services.json/plist 또는 firebase > 프로젝트 개요 >  프로젝트 설정에서 얻을 수 있다
// 플랫폼별 개별 설정이 필요하다
// 참고 형태는 찾기쉽게 작성한 참고일뿐 다를 수 있다
  await Firebase.initializeApp(
    options: FirebaseOptions(
      apiKey: API_KEY_ANDROID, // AIza... 형태
      appId: APP_ID_ANDROID,  // 1:8843...android:84.. 형태
      messagingSenderId: SENDER_ID_ANDROID, // 숫자 일련번호 형태
      projectId: PROJECT_ID_ANDROID, // 앱이름-숫자 형태
    ),
  );
  
  // 백그라운드 설정
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

  // 앱일경우만 firebase setting 함수 실행
  if (!kIsWeb) {
    await setupFlutterNotifications();
  }

  runApp(const MyApp());
}

2. 백그라운드 설정

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


('vm:entry-point')
/*
 이 함수가 라이브러리 외부에서 호출될 가능성이 없는 경우, 
 @pragma('vm:entry-point')로 지정하여 AOT 컴파일러가 해당 함수를 컴파일하지 않도록 하여
 컴파일 시간과 크기를 줄일 수 있습니다.
*/

// 백그라운드 핸들러
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp(options: DefaultFirebaseOptions.currentPlatform);
  await setupFlutterNotifications(); // firebase 세팅 아래에 설명
  showFlutterNotification(message); // 메시지 보이기 아래에 설명
  // If you're going to use other Firebase services in the background, such as Firestore,
  // make sure you call `initializeApp` before using other Firebase services.
  print('Handling a background message ${message.messageId}');
}

3. firebase setting

/// 셋팅 메소드
Future<void> setupFlutterNotifications() async {
  if (isFlutterLocalNotificationsInitialized) {
    return;
  }
  channel = const AndroidNotificationChannel(
    'high_importance_channel', // id는 AndroidManifest.xml 파일에서 설정한 default_notification_channel_id 값과 같아야한다 
    'High Importance Notifications', // title
    description:
        'This channel is used for important notifications.', // description
    importance: Importance.high,
  );
  flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
  await flutterLocalNotificationsPlugin
      .resolvePlatformSpecificImplementation<
          AndroidFlutterLocalNotificationsPlugin>()
      ?.createNotificationChannel(channel);
  // iOS foreground notification 권한
  await FirebaseMessaging.instance.setForegroundNotificationPresentationOptions(
    alert: true,
    badge: true,
    sound: true,
  );
  // IOS background 권한 체킹 , 요청
  await FirebaseMessaging.instance.requestPermission(
    alert: true,
    announcement: false,
    badge: true,
    carPlay: false,
    criticalAlert: false,
    provisional: false,
    sound: true,
  );
  // 토큰 요청
  getToken();
  // 셋팅flag 설정
  isFlutterLocalNotificationsInitialized = true;
}
  • 토큰 가져오기 (테스트 및 서버에 보낼때 사용)
    getToken을 사용하면 ios에서 자동으로 APNs을 설정하고 FCM 토큰을 반환한다고 하는데 일단 확실히 하기위해서 getAPNSToken을 사용
Future<void> getToken() async {
  String? token;
  FirebaseMessaging messaging = FirebaseMessaging.instance;
  
  // 플랫폼 별 토큰 가져오기
  if (defaultTargetPlatform == TargetPlatform.iOS) {
    token = await messaging.getAPNSToken();
  } else {
    token = await messaging.getToken();
  }

  print('FCM Token: $token');
}
  • forground에서 알림 표시하기
void showFlutterNotification(RemoteMessage message) {
  RemoteNotification? notification = message.notification;
  AndroidNotification? android = message.notification?.android;
  if (notification != null && android != null && !kIsWeb) {
    flutterLocalNotificationsPlugin.show(
      notification.hashCode,
      notification.title,
      notification.body,
      NotificationDetails(
        android: AndroidNotificationDetails(
          channel.id,
          channel.name,
          channelDescription: channel.description,
          // TODO add a proper drawable resource to android, for now using
          //      one that already exists in example app.
          icon: 'launch_background',
        ),
      ),
    );
  }
}

4. 함수 호출

...
// 가장 상단 페이지에서 한번 호출해준다

 
  void initState() {
    super.initState();

    // foreground 수신처리
    FirebaseMessaging.onMessage.listen(showFlutterNotification);

    // background 수신처리
    FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);

    // 알림 클릭시 함수처리
    FirebaseMessaging.onMessageOpenedApp.listen((message) {
    	// 특정 페이지로 가고 싶게한다면 추가 설정이 필요하다
      print(message);
    });
  }

5. firebase에서 테스트 메시지로 알림 테스트

  • firebase 프로젝트 > 참여 > messaging > 알림 메시지 만들기

  • 알림 내용 작성

  • 토큰 추가 및 테스트

    앞서 만든 getToken 메서드에서 얻은 토큰값을 추가하여 해당기기로 알림 테스트를 진행할 수 있다.

! 알림 테스트는 실기기에서 진행해야 정상적으로 진행된다

profile
프론트엔드

0개의 댓글