[flutter] shared_preferences 를 사용하여 알림 수신 여부를 저장하는 방법은 무엇인가요?
  1. shared_preferences 패키지를 프로젝트에 추가해주세요. pubspec.yaml 파일에 다음을 추가합니다:

    dependencies:
      flutter:
        sdk: flutter
      shared_preferences: ^2.0.0
    
  2. pubspec.yaml 파일을 저장한 후, 패키지를 가져오기 위해 터미널에서 flutter pub get을 실행합니다.

  3. 이제 shared_preferences를 사용하여 알림 수신 여부를 저장하고 가져오는 코드를 작성할 수 있습니다. 예를 들어, NotificationPreferences라는 클래스를 생성하고 그 안에 setNotificationEnabledisNotificationEnabled 메서드를 추가해보겠습니다.

    import 'package:flutter/material.dart';
    import 'package:shared_preferences/shared_preferences.dart';
       
    class NotificationPreferences {
      static const String _keyEnabled = 'notification_enabled';
       
      static Future<void> setNotificationEnabled(bool enabled) async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        prefs.setBool(_keyEnabled, enabled);
      }
       
      static Future<bool> isNotificationEnabled() async {
        SharedPreferences prefs = await SharedPreferences.getInstance();
        return prefs.getBool(_keyEnabled) ?? false;
      }
    }
    
  4. 이제 setNotificationEnabled 메서드를 사용하여 알림 수신 여부를 저장할 수 있습니다. 예를 들어, 스위치 위젯이 있는 설정 화면에서 알림 수신을 변경하면 호출될 수 있습니다.

    Switch(
      value: isNotificationEnabled,
      onChanged: (value) {
        setState(() {
          // 알림 수신 여부를 업데이트하고 저장합니다.
          NotificationPreferences.setNotificationEnabled(value);
        });
      },
    ),
    
  5. isNotificationEnabled 메서드를 사용하여 알림 수신 여부를 가져올 수 있습니다. 예를 들어, 알림을 보낼 때 수신 여부를 확인할 수 있습니다.

    bool notificationEnabled = await NotificationPreferences.isNotificationEnabled();
    if (notificationEnabled) {
      // 알림을 보내세요.
    }
    

이제, shared_preferences를 사용하여 알림 수신 여부를 저장하고 가져올 수 있게 되었습니다. 이를 통해 사용자가 알림을 활성화 또는 비활성화할 수 있는 유연한 설정을 구현할 수 있습니다.

더 자세한 내용은 shared_preferences 패키지 문서를 참조하시기 바랍니다.