[Flutter] notification 알림 주는 법

2023. 9. 23. 14:26·Web & Android/Flutter

Notification

  • push notification - 서버에서 보내는 알림
  • local notification - 앱 자체에서 실행하는 알림


패키지 설치

  • pubspec.yaml에 flutter_local_notifications: ^9.1.5 추가 후 pub get

Android 셋팅

  • android/app/src/main/res/drawable 폴더에 알림에 띄울 아이콘 용 넣기
  • 흰색 아웃라인만 있는 .png만 허용

 

iOS 셋팅

  • 프로젝트 내의 ios/Runner/AppDelegate.swift 파일에 코드 추가
    • GeneratedPluginRegistrant.register(with: self) 이런 코드 윗줄에 복붙
if #available(iOS 10.0, *) {
      UNUserNotificationCenter.current().delegate = self as? UNUserNotificationCenterDelegate
}

 

알림 띄우려면 실행할 코드

  • notifications.initialize() 이런 코드를 한 번 실행해야 알림 서비스가 잘 작동
  • notification.dart 파일 만들어서 이런 코드 복붙
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: 함수명추가
  );
}
  • local_notification 요즘버전은 IOSInitializationSettings() 부분을 DarwinInitializationSettings() 로 바꿔야 잘될 수 있음

⇒ main.dart 파일에 사용 → import 하기

  • MyApp 위젯이 로드될 때 저 함수 안의 내용이 실행됨
import 'notification.dart';

@override
void initState() {
    super.initState();
    initNotification(); //추가함
    getData();
}

 

알림 띄우는 코드

  • notifications.show() 코드 쓰면 알림 듬
//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)
    );
}

⇒ local_notification 요즘버전은 IOSNotificationDetails를 DarwinNotificationDetails로 바꿔야 잘될 수 있음

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

전체 코드

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

final notifications = FlutterLocalNotificationsPlugin();

//1. 앱로드시 실행할 기본설정
initNotification(context) 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: (payload) {
      Navigator.push(
        context,
        MaterialPageRoute(
          builder: (context) => Text('새로운페이지'),
        ),
      );
    }
  );
}

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

  // 안드로이드
  var androidDetails = AndroidNotificationDetails(
    '유니크한 알림 채널 ID',
    '알림종류 설명',
    priority: Priority.high,   // 중요도
    importance: Importance.max,  // 중요도
    color: Color.fromARGB(255, 255, 0, 0),  // 알림 색상
  );

  // ios
  var iosDetails = IOSNotificationDetails(
    presentAlert: true,  // 알림 여부
    presentBadge: true,  // 뱃지 여부
    presentSound: true,  // 소리 여부
  );

  // 알림 id, 제목, 내용 맘대로 채우기
  notifications.show(
      1,
      '제목1',
      '내용1',
      NotificationDetails(android: androidDetails, iOS: iosDetails),
      payload: '부가정보'
  );
}

주기적인 알림

  • notification.dart 상단에 추가
import 'package:timezone/data/latest_all.dart' as tz;
import 'package:timezone/timezone.dart' as tz;

 

특정 시간에 알림 띄우기

  • notifications.zonedSchedule() 쓰면 알림 띄워주는데 입력한 시간에 알림 띄워주는 기능
  • 타임존에 따른 현재 시간은 tz.TZDateTime.now(tz.local)
  • uiLocalNotificationDateInterpretation: 은 iOS 10 미만 기기들 호환을 위한 기능
showNotification2() async {

  tz.initializeTimeZones();

  var androidDetails = const AndroidNotificationDetails(
    '유니크한 알림 ID',
    '알림종류 설명',
    priority: Priority.high,
    importance: Importance.max,
    color: Color.fromARGB(255, 255, 0, 0),
  );
  var iosDetails = const IOSNotificationDetails(
    presentAlert: true,
    presentBadge: true,
    presentSound: true,
  );

// 특정 시간 알림
  notifications.zonedSchedule(
      2,
      '제목2',
      '내용2',
      tz.TZDateTime.now(tz.local).add(Duration(seconds: 5)),
      NotificationDetails(android: androidDetails, iOS: iosDetails),
      androidAllowWhileIdle: true,
      uiLocalNotificationDateInterpretation:
      UILocalNotificationDateInterpretation.absoluteTime
  );
}

 

주기적 알림

  • notifications.periodicallyShow
  • RepeatInterval.daily 부분을 맘대로 바꾸면 됨 → weekly, hourly 이런 거 있음
  • daily로 설정해놓으면 코드가 실행되는 시점으로부터 정확히 24시간 후 알림 뜸
notifications.periodicallyShow(
    3,
    '제목3',
    '내용3',
    RepeatInterval.daily,
    NotificationDetails(android: androidDetails, iOS: iosDetails),
    androidAllowWhileIdle: true
);

 

예정된 알림 취소하는 법

  • 0은 알림 번호
  • 0 자리에 알림 번호 적으면 해당 알림이 취소됨
await notifications.cancel(0);

 

모든 예정된 알림 삭제

await notifications.cancelAll();

 

매일 7시 알림

  • matchDateTimeComponents: DateTimeComponents.time 있어야 함
    • .time 대신 .dayOfWeekAndTime 이런 파라미터가 있으면 같은 요일, 시간 매주 알림을 띄워줌
    • .time 대신 .dayOfMonthAndTime 이런 파라미터가 있으면 같은 날짜, 시간 매달 알림을 띄워줌
    • .time 대신 .dateAndTime 이런 파라미터가 있으면 같은 날짜, 시간 매년 알림을 띄워줌
  • 함수 생성
    makeDate(hour, min, sec){
      var now = tz.TZDateTime.now(tz.local);
      var when = tz.TZDateTime(tz.local, now.year, now.month, now.day, hour, min, sec);
      if (when.isBefore(now)) {
        return when.add(Duration(days: 1));
      } else {
        return when;
      }
    }
  • zonedSchedule 안에 넣어서 사용하면 됨
    notifications.zonedSchedule(
          2,
          '제목2',
          '내용2',
          makeDate(8,30,0),
          NotificationDetails(android: androidDetails, iOS: iosDetails),
          androidAllowWhileIdle: true,
          uiLocalNotificationDateInterpretation:
          UILocalNotificationDateInterpretation.absoluteTime,
          matchDateTimeComponents: DateTimeComponents.time
    );

서버가 보내는 Push 알림

  • Firebase Cloud Message 로 메시지를 보내서 전송해야 함

전체 코드

저작자표시 비영리 변경금지 (새창열림)

'Web & Android > Flutter' 카테고리의 다른 글

[Flutter] 유용한 패키지들  (0) 2023.09.23
[Flutter] 반응형 스크린 사이즈  (1) 2023.09.23
[Flutter] GridView, CustomScrollView 프로필 페이지 만들기  (0) 2023.09.23
[Flutter] Provider : store 여러개 & GET 요청  (0) 2023.09.23
[Flutter] 친구 팔로우 하기  (1) 2023.09.23
'Web & Android/Flutter' 카테고리의 다른 글
  • [Flutter] 유용한 패키지들
  • [Flutter] 반응형 스크린 사이즈
  • [Flutter] GridView, CustomScrollView 프로필 페이지 만들기
  • [Flutter] Provider : store 여러개 & GET 요청
woojin._.
woojin._.
여러가지 개발을 해보며 발생하는 이야기들에 대한 블로그입니다:)
  • woojin._.
    Jin's Dev Story
    woojin._.
  • 전체
    오늘
    어제
    • 분류 전체보기 (829)
      • Tools (25)
        • eGovFrame (3)
        • GeoServer (3)
        • QGIS (2)
        • LabelImg (2)
        • Git (6)
        • GitHub (1)
        • Eclipse (7)
        • Visual Studio (1)
      • Web & Android (121)
        • SpringBoot (37)
        • Three.js (2)
        • Spring Data JPA (9)
        • 스프링 부트 쇼핑몰 프로젝트 with JPA (25)
        • Thymeleaf (4)
        • Spring Security (15)
        • Flutter (29)
      • Programming Language (61)
        • JAVA (27)
        • JavaScript (14)
        • Dart (2)
        • Python (15)
        • PHP (3)
      • Database (43)
        • PostgreSQL (32)
        • MYSQL (7)
        • Oracle (3)
        • MSSQL (1)
      • SERVER (17)
        • TCP_IP (3)
        • 리눅스 (7)
        • AWS (7)
      • Coding Test (445)
        • 백준[JAVA] (108)
        • 프로그래머스[JAVA] (260)
        • 알고리즘 고득점 Kit[JAVA] (3)
        • SQL 고득점 Kit[ORACLE] (74)
      • CS 지식 (49)
        • [자료구조] (14)
        • [네트워크] (12)
        • [데이터베이스] (10)
        • [알고리즘] (9)
        • [운영체제] (4)
      • 기타 (6)
      • 자격증 & 공부 (62)
        • 정보처리기사 (2)
        • SQLD (6)
        • 네트워크관리사 2급 (5)
        • 리눅스마스터 1급 (44)
        • 리눅스마스터 2급 (1)
        • ISTQB (3)
        • 시스템보안 (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 인기 글

  • 태그

    백준
    postgresql
    Java
    pcce 기출문제
    CS지식
    프로그래머스
    리눅스
    데이터베이스
    플러터
    programmers
    backjoon
    리눅스마스터 1급
    Spring Security
    springboot
    spring
    DB
    스프링
    CS
    시큐리티
    스프링부트
    Oracle
    Linux
    Flutter
    JPA
    스프링 부트 쇼핑몰 프로젝트 with JPA
    데이터
    baekjoon
    python
    리눅스마스터
    자바
  • 최근 글

  • hELLO· Designed By정상우.v4.10.0
woojin._.
[Flutter] notification 알림 주는 법
상단으로

티스토리툴바