Front-End/Flutter

[Flutter] Local Notification

Voyage_dev 2023. 10. 28. 17:46

notification 종류는 2개가 있다. 서버에서 보내는 push notification / 앱 자체에서 실행하는 local notification

 

패키지 설치가 필요

flutter_local_notifications: ^9.1.5

  • android/app/src/main/res/drawable 폴더에 알림을 띄울 아이콘용 이미지를 하나 넣으면 된다
  • 주의사항은 알림용 아이콘은 흰색 아웃라인만 있는 .png만 허용된다

  • 만약 불가능한 이미지를 넣으면 이렇게 보인다

  • 아이폰은 필요없다 그냥 앱 로고 그대로 쓰기 때문

iOS 셋팅

ios/Runner/AppDelegate.swift 파일

if #available(iOS 10.0, *) {
      UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
}
  • iOS 버전마다 앱 알림을 관리하는 방법이 달라서 추가하는 코드

알림 띄우려면 일단 먼저 실행할 코드

import 'package:flutter/material.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';

final notifications = FlutterLocalNotificationsPlugin();

//1. 앱로드시 실행할 기본설정
initNotification() async {

  //안드로이드용 아이콘파일 이름
  var androidSetting = AndroidInitializationSettings('app_icon');

  //ios에서 앱 로드시 유저에게 권한요청하려면
  var iosSetting = IOSInitializationSettings(
    requestAlertPermission: true,
    requestBadgePermission: true,
    requestSoundPermission: true,
  );

  var initializationSettings = InitializationSettings(
      android: androidSetting,
      iOS: iosSetting
  );
  await notifications.initialize(
    initializationSettings,
    //알림 누를때 함수실행하고 싶으면
    //onSelectNotification: 함수명추가
  );
}
  • notifications.initialize() 이런 코드를 한 번 실행해야 알림 서비스가 잘 작동.
  • notification.dart 파일 만들어서 코드 복붙.
  • local_notification 요즘버전은
    • IOSInitializationSettings() 부분을 DarwinInitializationSettings() 로 바꿔야 잘될 수 있다.
// main.dart
import 'notification.dart';
@override
void initState() {
    super.initState();
    initNotification(); //추가함
    getData();
}
  • 위젯이 로드될 때 함수 안의 내용이 실행되도록 initState()로 실행

알림 띄우는 코드

//2. 이 함수 원하는 곳에서 실행하면 알림 뜸
showNotification() async {

  var androidDetails = AndroidNotificationDetails(
    '유니크한 알림 채널 ID',
    '알림종류 설명',
    priority: Priority.high,
    importance: Importance.max,
    color: Color.fromARGB(255, 255, 0, 0),
  );

  var iosDetails = IOSNotificationDetails(
    presentAlert: true,
    presentBadge: true,
    presentSound: true,
  );

  // 알림 id, 제목, 내용 맘대로 채우기
  notifications.show(
      1,
      '제목1',
      '내용1',
      NotificationDetails(android: androidDetails, iOS: iosDetails)
    );
}
  • notifications.show() 이런 코드 쓰면 알림이 뜬다
  • 함수로 만드는게 좋다
  • local_notification 요즘버전은
    • IOSNotificationDetails를 DarwinNotificationDetails로 바꿔야 잘될 수 있습니다

역시 패키지 사용법일 뿐이라 복붙해서 수정하면 된다.

  • 알림 ID는 알림 채널 ID 만드는 곳인데 비슷한 알림들을 모으는 그룹 같은 거라고 생각하면 되고 알아서 아무 글자나 넣으면 끝
  • 알림 설명은 알림 채널 설명 적으면 끝. 안드로이드에서 알림 길게 누르면 나오는 문자임
  • color : 파라미터 수정하면 안드로이드에서 알림 아이콘 색상이 변경
  • priority, importance를 수정하면 안드로이드에서 알림 소리, 팝업 띄울지 말지를 결정가능.
  • iosDetails 부분에 presentSound : false로 바꿔주면 iOS 알림 보여줄 때 소리 켤지말지 선택가능.
  • 실제 알림 제목, 내용은 notifications.show() 안에서 수정하면 된다. 안에 있는 숫자는 개별 알림마다 넣을 유니크한 번호임
Scaffold(
      floatingActionButton: FloatingActionButton(child: Text('+'),
        onPressed: (){
          showNotification();
        },
      ),

 

출처 : 코딩애플