[flutter] 플러터에서 훅(hook)을 활용하여 로컬 알림 기능 추가하기

플러터를 사용하여 모바일 앱을 개발하는 경우, 로컬 알림 기능을 추가하는 것은 매우 일반적입니다. 이번 포스트에서는 플러터의 훅(hook)을 활용하여 간단한 로컬 알림 기능을 추가하는 방법을 알아보겠습니다.

1. flutter_local_notifications 라이브러리 추가하기

먼저, flutter_local_notifications 라이브러리를 사용하여 앱에 로컬 알림 기능을 추가할 수 있습니다. pubspec.yaml 파일에 다음과 같이 라이브러리를 추가합니다.

dependencies:
  flutter_local_notifications: ^5.0.0

이후 터미널에서 flutter pub get 명령어를 실행하여 라이브러리를 다운로드 받습니다.

2. 훅(hook) 함수 작성하기

알림을 생성하고 예약하는 데 사용할 훅(hook) 함수를 작성합니다. 아래는 예시 코드입니다.

import 'package:flutter_local_notifications/flutter_local_notifications.dart';

Future<void> scheduleNotification() async {
  var androidPlatformChannelSpecifics = AndroidNotificationDetails(
      'channel_id', 'channel_name', 'channel_description',
      importance: Importance.max, priority: Priority.high, ticker: 'ticker');
  var iOSPlatformChannelSpecifics = IOSNotificationDetails();
  var platformChannelSpecifics = NotificationDetails(
      android: androidPlatformChannelSpecifics, iOS: iOSPlatformChannelSpecifics);

  await flutterLocalNotificationsPlugin.zonedSchedule(
      0,
      'scheduled title',
      'scheduled body',
      tz.TZDateTime.now(tz.local).add(const Duration(seconds: 5)),
      platformChannelSpecifics,
      androidAllowWhileIdle: true,
      uiLocalNotificationDateInterpretation:
          UILocalNotificationDateInterpretation.absoluteTime);
}

3. 앱 UI에 연동하기

훅 함수를 사용하여 알림을 예약하는 방법은 여러 가지가 있겠지만, UI 요소를 통해 사용자가 직접 예약할 수 있도록 하는 것이 일반적입니다. 여기서는 버튼을 눌렀을 때 알림이 예약되도록 하는 간단한 예시 코드를 보여드리겠습니다.

ElevatedButton(
  onPressed: () {
    scheduleNotification();
  },
  child: Text('Schedule Notification'),
)

마무리

이제, 플러터의 훅(hook)을 활용하여 로컬 알림 기능을 간단하게 추가하는 방법을 살펴봤습니다. 이를 통해, 사용자에게 더 나은 앱 사용 경험을 제공할 수 있게 되었습니다. 더 많은 기능을 추가하여 더욱 풍부한 사용자 경험을 제공하는 애플리케이션을 개발해보세요!

참고 자료:

플러터로 로컬 알림 기능을 추가하는 방법에 대해 궁금한 점이 있으면 언제든지 질문해주세요!