알림(Notification)은 사용자에게 중요한 정보를 전달하거나 앱의 이벤트를 공지하는 데 필수적인 요소입니다. Flutter를 사용하면 로컬 알림과 푸시 알림을 쉽게 구현할 수 있습니다. 이번 글에서는 Flutter에서 알림을 구현하는 방법을 단계별로 설명하겠습니다.
1. 로컬 알림 구현
로컬 알림은 앱이 포그라운드 상태일 때 사용자에게 알림을 보내는 데 사용됩니다. flutter_local_notifications 패키지를 사용하여 로컬 알림을 구현할 수 있습니다.
1.1 flutter_local_notifications 패키지 설치
먼저 pubspec.yaml 파일에 flutter_local_notifications 패키지를 추가합니다.
dependencies:
flutter:
sdk: flutter
flutter_local_notifications: ^9.0.0
그리고 pub get 명령어를 실행하여 패키지를 설치합니다.
1.2 Android 및 iOS 설정
Android와 iOS에서 로컬 알림을 사용할 수 있도록 설정합니다.
Android 설정:
android/app/src/main/AndroidManifest.xml 파일에 다음 코드를 추가합니다.
<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
<application>
...
<receiver
android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationReceiver"
android:exported="true"/>
<receiver
android:name="com.dexterous.flutterlocalnotifications.ScheduledNotificationBootReceiver"
android:enabled="true"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.BOOT_COMPLETED"/>
<action android:name="android.intent.action.MY_PACKAGE_REPLACED"/>
</intent-filter>
</receiver>
</application>
iOS 설정:
ios/Runner/Info.plist 파일에 다음 코드를 추가합니다.
<key>UIBackgroundModes</key>
<array>
<string>fetch</string>
<string>remote-notification</string>
</array>
1.3 로컬 알림 구현
이제 Flutter 코드에서 로컬 알림을 구현합니다.
import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin;
@override
void initState() {
super.initState();
flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();
const AndroidInitializationSettings initializationSettingsAndroid =
AndroidInitializationSettings('@mipmap/ic_launcher');
const IOSInitializationSettings initializationSettingsIOS =
IOSInitializationSettings();
const InitializationSettings initializationSettings =
InitializationSettings(
android: initializationSettingsAndroid, iOS: initializationSettingsIOS);
flutterLocalNotificationsPlugin.initialize(initializationSettings);
}
Future<void> _showNotification() async {
const AndroidNotificationDetails androidPlatformChannelSpecifics =
AndroidNotificationDetails('your_channel_id', 'your_channel_name',
channelDescription: 'your_channel_description',
importance: Importance.max,
priority: Priority.high,
showWhen: false);
const NotificationDetails platformChannelSpecifics =
NotificationDetails(android: androidPlatformChannelSpecifics);
await flutterLocalNotificationsPlugin.show(
0,
'Test Notification',
'This is the notification body',
platformChannelSpecifics,
payload: 'item x',
);
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Flutter Notifications'),
),
body: Center(
child: ElevatedButton(
onPressed: _showNotification,
child: Text('Show Notification'),
),
),
),
);
}
}
위 코드는 간단한 로컬 알림을 생성하고 표시하는 예제입니다. flutterLocalNotificationsPlugin.show 메서드를 사용하여 알림을 생성하고 표시합니다.
2. 푸시 알림 구현
푸시 알림은 서버에서 전송되어 앱이 백그라운드나 종료된 상태에서도 사용자에게 알림을 보낼 수 있습니다. 푸시 알림을 구현하기 위해 Firebase Cloud Messaging(FCM)을 사용합니다.
2.1 firebase_messaging 패키지 설치
pubspec.yaml 파일에 firebase_messaging 패키지를 추가합니다.
dependencies:
flutter:
sdk: flutter
firebase_core: ^1.10.0
firebase_messaging: ^11.0.0
그리고 pub get 명령어를 실행하여 패키지를 설치합니다.
2.2 Android 및 iOS 설정
Android와 iOS에서 FCM을 사용할 수 있도록 설정합니다.
Android 설정:
android/app/src/main/AndroidManifest.xml 파일에 다음 코드를 추가합니다.
<uses-permission android:name="android.permission.INTERNET"/>
<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>
iOS 설정:
ios/Runner/Info.plist 파일에 다음 코드를 추가합니다.
<key>FirebaseAppDelegateProxyEnabled</key>
<false/>
<key>UIBackgroundModes</key>
<array>
<string>fetch</string>
<string>remote-notification</string>
</array>
2.3 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 Notifications'),
),
body: Center(
child: Text('Push Notifications with Firebase Messaging'),
),
),
);
}
}
위 코드는 Firebase Cloud Messaging을 초기화하고 푸시 알림을 처리하는 예제입니다. FirebaseMessaging.onMessage를 사용하여 앱이 포그라운드 상태일 때 푸시 알림을 처리하고, FirebaseMessaging.onMessageOpenedApp를 사용하여 사용자가 알림을 클릭하여 앱을 열었을 때 이벤트를 처리합니다.
결론
Flutter에서 로컬 알림과 푸시 알림을 구현하면 사용자에게 중요한 정보를 전달하고 앱의 이벤트를 효과적으로 공지할 수 있습니다. flutter_local_notifications 패키지를 사용하여 로컬 알림을 구현하고, Firebase Cloud Messaging을 사용하여 푸시 알림을 구현할 수 있습니다. 이번 글에서 소개한 방법들을 활용하여 Flutter 애플리케이션에서 알림 기능을 구현해보세요. 알림 기능을 통해 사용자 경험을 크게 향상시킬 수 있습니다.
'Flutter' 카테고리의 다른 글
Flutter의 로컬 알림(Local Notifications) 설정 (0) | 2025.01.20 |
---|---|
Flutter의 푸시 알림(Push Notifications) 설정 (0) | 2025.01.20 |
Flutter의 채팅 애플리케이션(Chat Application) 만들기 (2) | 2025.01.18 |
Flutter의 사용자 목록(User List) 화면 만들기 (0) | 2025.01.17 |
Flutter의 설정 화면(Settings Screen) 만들기 (0) | 2025.01.17 |