[flutter] 플러터 Riverpod를 이용한 푸시 알림 처리 방법

푸시 알림은 사용자에게 중요한 정보나 이벤트에 대한 알림을 보내는 데 사용되는 중요한 기능입니다. 이번 포스트에서는 플러터 앱에서 Riverpod 상태 관리 라이브러리를 사용하여 푸시 알림을 처리하는 방법에 대해 알아보겠습니다.

1. Firebase 설정

Firebase를 사용하여 푸시 알림을 구현할 수 있습니다. Firebase 콘솔에 접속하여 프로젝트를 생성하고, Firebase 푸시 알림을 설정해야 합니다. 알림을 보내고자 하는 앱의 패키지 이름을 입력하고, 서버 키를 생성하여 획득합니다.

2. Riverpod 설치

터미널에서 다음 명령어를 사용하여 Riverpod 패키지를 설치합니다:

pubspec.yaml

dependencies:
  flutter:
    sdk: flutter
  riverpod: ^1.0.0

3. Firebase Messaging 패키지 설치

Riverpod와 함께 Firebase Messaging 패키지를 사용하여 Firebase 푸시 알림을 처리할 수 있습니다. pubspec.yaml 파일에 firebase_messaging 패키지를 추가합니다:

pubspec.yaml

dependencies:
  flutter:
    sdk: flutter
  riverpod: ^1.0.0
  firebase_messaging: ^11.0.0

4. 푸시 알림 처리 코드 작성

푸시 알림을 처리하는 코드를 작성해보겠습니다. 다음과 같이 FirebaseMessaging 클래스의 인스턴스를 생성하고, 토큰을 가져오는 함수를 작성합니다:

import 'package:firebase_messaging/firebase_messaging.dart';

class PushNotificationService {
  final FirebaseMessaging _messaging = FirebaseMessaging.instance;

  Future<String> getDeviceToken() async {
    String? token = await _messaging.getToken();
    return token!;
  }
}

5. 상태 관리 코드 작성

Riverpod를 사용하여 앱 전역에서 푸시 알림을 처리하기 위해 상태 관리를 설정해보겠습니다. 다음과 같이 Provider를 사용하여 알림을 저장하는 상태 클래스를 정의합니다:

import 'package:riverpod/riverpod.dart';

class PushNotificationState {
  final List<String> notifications;

  PushNotificationState(this.notifications);
}

final pushNotificationProvider =
    StateNotifierProvider<PushNotificationNotifier, PushNotificationState>(
  (ref) => PushNotificationNotifier(ref.read),
);

class PushNotificationNotifier extends StateNotifier<PushNotificationState> {
  final Reader _read;

  PushNotificationNotifier(this._read) : super(PushNotificationState([]));

  void addNotification(String notification) {
    state = PushNotificationState([...state.notifications, notification]);
  }
}

6. 푸시 알림 처리 코드 작성

Firebase Messaging을 사용하여 푸시 알림을 처리하는 코드를 작성해보겠습니다. 푸시 알림을 수신한 경우, onMessage, onBackgroundMessage, onResume, onLaunch 등의 콜백 함수가 호출됩니다. 다음은 onMessage 콜백에서 푸시 알림을 처리하는 코드입니다:

class PushNotificationService {
  // ...

  void initializePushNotification() {
    FirebaseMessaging.onMessage.listen((RemoteMessage message) {
      final notification = message.notification;
      if (notification != null) {
        final body = notification.body;
        _read(pushNotificationProvider.notifier).addNotification(body!);
      }
    });
  }
}

7. UI 업데이트 코드 작성

마지막으로 UI를 업데이트하는 코드를 작성해보겠습니다. Consumer 위젯을 사용하여 pushNotificationProvider를 구독하고, 알림이 추가될 때마다 UI가 업데이트되도록 설정할 수 있습니다:

Widget build(BuildContext context) {
  return Scaffold(
    appBar: AppBar(
      title: Text('푸시 알림'),
    ),
    body: Consumer(
      builder: (context, watch, child) {
        final notifications = watch(pushNotificationProvider).notifications;
        return ListView.builder(
          itemCount: notifications.length,
          itemBuilder: (context, index) {
            final notification = notifications[index];
            return ListTile(
              title: Text(notification),
            );
          },
        );
      },
    ),
  );
}

결론

이렇게 Riverpod와 Firebase Messaging을 함께 사용하여 플러터 앱에서 푸시 알림을 처리할 수 있습니다. Riverpod를 사용하면 앱 전역에서 푸시 알림 상태를 관리할 수 있고, Firebase Messaging을 이용하여 푸시 알림을 처리할 수 있습니다. 푸시 알림은 사용자 경험을 향상시키고, 중요한 정보를 효과적으로 전달하는 데 도움이 될 것입니다.

참고 자료