푸시 알림(Push Notifications)은 사용자에게 실시간으로 중요한 정보를 전달할 수 있는 강력한 도구입니다. Flutter에서는 Firebase Cloud Messaging(FCM)을 사용하여 푸시 알림을 쉽게 설정할 수 있습니다. 이번 글에서는 Flutter에서 푸시 알림을 설정하는 방법을 단계별로 설명하겠습니다.
1. Firebase 프로젝트 생성 및 설정
먼저, Firebase 콘솔에서 새 프로젝트를 생성하고 Flutter 앱과 연동해야 합니다.
1.1 Firebase 프로젝트 생성
- Firebase 콘솔에 로그인하고 새 프로젝트를 만듭니다.
- 프로젝트 이름을 입력하고 프로젝트를 생성합니다.
1.2 Firebase 앱 추가
- Firebase 프로젝트 대시보드에서 Android와 iOS 앱을 추가합니다.
- Android의 경우, google-services.json 파일을 다운로드하여 android/app 폴더에 추가합니다.
- iOS의 경우, GoogleService-Info.plist 파일을 다운로드하여 ios/Runner 폴더에 추가합니다.
2. Firebase 플러그인 추가
Flutter 프로젝트에 Firebase 플러그인을 추가합니다.
pubspec.yaml 파일에 다음 의존성을 추가합니다.
dependencies:
  flutter:
    sdk: flutter
  firebase_core: ^1.10.0
  firebase_messaging: ^11.0.0
그리고 pub get 명령어를 실행하여 패키지를 설치합니다.
3. Android 및 iOS 설정
3.1 Android 설정
android/app/src/main/AndroidManifest.xml 파일에 다음 코드를 추가합니다.
<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application>
    ...
    <service android:name="com.google.firebase.messaging.FirebaseMessagingService"
        android:exported="true">
        <intent-filter>
            <action android:name="com.google.firebase.MESSAGING_EVENT"/>
        </intent-filter>
    </service>
</application>
3.2 iOS 설정
ios/Runner/Info.plist 파일에 다음 코드를 추가합니다.
<key>FirebaseAppDelegateProxyEnabled</key>
<false/>
<key>UIBackgroundModes</key>
<array>
    <string>fetch</string>
    <string>remote-notification</string>
</array>
그리고 ios/Runner 디렉토리의 AppDelegate.swift 파일을 수정하여 Firebase 초기화 코드를 추가합니다.
import UIKit
import Flutter
import Firebase
@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
  override func application(
    _ application: UIApplication,
    didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
  ) -> Bool {
    FirebaseApp.configure()
    if #available(iOS 10.0, *) {
      UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
    }
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
  }
}
4. FCM 초기화 및 푸시 알림 처리
Flutter 코드에서 FCM을 초기화하고 푸시 알림을 처리합니다.
import 'package:flutter/material.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:firebase_messaging/firebase_messaging.dart';
void main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
  FirebaseMessaging.onBackgroundMessage(_firebaseMessagingBackgroundHandler);
  runApp(MyApp());
}
Future<void> _firebaseMessagingBackgroundHandler(RemoteMessage message) async {
  await Firebase.initializeApp();
  print("Handling a background message: ${message.messageId}");
}
class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
  final FirebaseMessaging _firebaseMessaging = FirebaseMessaging.instance;
  @override
  void initState() {
    super.initState();
    _firebaseMessaging.requestPermission();
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      print('Got a message whilst in the foreground!');
      print('Message data: ${message.data}');
      if (message.notification != null) {
        print('Message also contained a notification: ${message.notification}');
      }
    });
    FirebaseMessaging.onMessageOpenedApp.listen((RemoteMessage message) {
      print('A new onMessageOpenedApp event was published!');
      Navigator.pushNamed(context, '/message', arguments: message);
    });
  }
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Push Notifications'),
        ),
        body: Center(
          child: Text('Push Notifications with Firebase Messaging'),
        ),
      ),
    );
  }
}
5. 푸시 알림 테스트
이제 Firebase 콘솔에서 직접 푸시 알림을 보내어 테스트할 수 있습니다.
- Firebase 콘솔에서 Cloud Messaging을 선택합니다.
- 새 메시지 작성을 클릭합니다.
- 메시지 텍스트와 제목을 입력하고 다음을 클릭합니다.
- 대상 선택에서 앱에 알림 전송을 선택합니다.
- 검토를 클릭하고, 전송을 클릭하여 테스트합니다.
결론
Flutter와 Firebase Cloud Messaging을 사용하여 푸시 알림을 설정하면 앱 사용자에게 중요한 정보를 실시간으로 전달할 수 있습니다. Firebase의 강력한 기능을 활용하면 푸시 알림을 쉽게 구현할 수 있으며, 이를 통해 사용자 경험을 크게 향상시킬 수 있습니다. 이번 글에서 소개한 방법들을 활용하여 Flutter 애플리케이션에서 푸시 알림 기능을 구현해보세요. 푸시 알림을 통해 사용자에게 중요한 정보를 빠르게 전달할 수 있습니다.
'Flutter' 카테고리의 다른 글
| Flutter의 채팅 애니메이션(Chat Animation) 구현하기 (0) | 2025.01.21 | 
|---|---|
| Flutter의 로컬 알림(Local Notifications) 설정 (0) | 2025.01.20 | 
| Flutter의 알림(Notification) 구현하기 (0) | 2025.01.19 | 
| Flutter의 채팅 애플리케이션(Chat Application) 만들기 (2) | 2025.01.18 | 
| Flutter의 사용자 목록(User List) 화면 만들기 (0) | 2025.01.17 |