flutter local notification 사용하기

패키지 설치

1
flutter pub add flutter_local_notifications

local notification 패키지를 설치해 줍니다.

Android

안드로이드 스크린샷

프로젝트경로/android/app/src/main/AndroidManifest.xml에 다음을 추가합니다.

1
2
android:showWhenLocked="true"
android:turnScreenOn="true"

IOS

Step 3: 프로젝트경로/ios/Runner/AppDelegate.swift에 다음을 Bool { } 내에 추가합니다.

1
2
3
if #available(iOS 10.0, *) { 
   UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
}

IOS 설정

Info.plist에 권한을 추가합니다.

설명은 되도록이면 자세하게 작성해주는 것이 좋습니다.
너무 간단하거나 적다면, 배포시에 리젝당하는 경우가 있습니다.

1
2
<key>NSUserNotificationsUsageDescription</key>
<string>This app needs notification permission to send notification of completion of timer.</string>

notification 코드 작성

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

class LocalNotification {
LocalNotification._();

static FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin =
FlutterLocalNotificationsPlugin();

static init() async {
// 알림 설정 초기화
AndroidInitializationSettings initializationSettingsAndroid =
const AndroidInitializationSettings('mipmap/ic_launcher'); // 앱 아이콘 설정

DarwinInitializationSettings initializationSettingsIOS =
const DarwinInitializationSettings(
requestAlertPermission: true,
requestBadgePermission: true,
requestSoundPermission: true,
);

InitializationSettings initializationSettings = InitializationSettings(
android: initializationSettingsAndroid, iOS: initializationSettingsIOS);

await flutterLocalNotificationsPlugin.initialize(initializationSettings);
}

static requestNotificationPermission() {
flutterLocalNotificationsPlugin
.resolvePlatformSpecificImplementation<
IOSFlutterLocalNotificationsPlugin>()
?.requestPermissions(
alert: true,
badge: true,
sound: true,
);
}

static Future<void> showNotification(
{required int id,
required String title,
required String body,
String? payload}) async {
const AndroidNotificationDetails androidDetails =
AndroidNotificationDetails('channelId', 'channelName',
channelDescription: 'channelDescription',
importance: Importance.max,
priority: Priority.high,
showWhen: false);

const DarwinNotificationDetails iosDetails =
DarwinNotificationDetails(badgeNumber: 1);

NotificationDetails generalNotificationDetails =
const NotificationDetails(android: androidDetails, iOS: iosDetails);

await flutterLocalNotificationsPlugin.show(
id,
title,
body,
generalNotificationDetails,
payload: payload,
);
}
}

로직 중간에 showNotification()를 사용하면 local notification이 작동되는 것을 확인 할 수 있습니다.

Share