플러터 GetX를 사용한 알림 설정 상세 가이드

2024. 6. 7. 21:00Flutter/Flutter Programming

반응형

플러터(Flutter)에서 GetX를 사용하여 알림 기능을 구현하는 방법을 알아보겠습니다.

이 가이드는 GetX의 상태 관리, 라우팅, 의존성 주입 등을 활용하여 알림 설정을 효율적으로 처리하는 방법을 다룹니다.

1. GetX 소개

GetX는 플러터의 상태 관리, 라우팅, 의존성 주입을 간편하게 해주는 패키지입니다. GetX의 주요 기능은 다음과 같습니다:

  • 상태 관리(State Management): 반응형 프로그래밍을 쉽게 구현할 수 있습니다.
  • 라우팅(Routing): 네비게이션과 라우팅을 간편하게 처리할 수 있습니다.
  • 의존성 주입(Dependency Injection): 의존성을 쉽게 주입하고 관리할 수 있습니다.

2. 프로젝트 설정

2.1. 새로운 플러터 프로젝트 생성

먼저 새로운 플러터 프로젝트를 생성합니다

flutter create notification_app
cd notification_app

2.2. pubspec.yaml 파일 업데이트

프로젝트의 pubspec.yaml 파일에 GetX와 알림 관련 패키지를 추가합니다

dependencies:
  flutter:
    sdk: flutter
  get: ^4.6.5
  flutter_local_notifications: ^9.0.0

그런 다음 패키지를 설치합니다

flutter pub get

3. 알림 설정

3.1. FlutterLocalNotificationsPlugin 초기화

lib/main.dart 파일을 열고 FlutterLocalNotificationsPlugin을 초기화합니다

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

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'Notification App',
      home: HomeScreen(),
    );
  }
}

class HomeScreen extends StatelessWidget {
  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

  HomeScreen() {
    final initializationSettingsAndroid = AndroidInitializationSettings('app_icon');
    final initializationSettingsIOS = IOSInitializationSettings();
    final initializationSettings = InitializationSettings(
      android: initializationSettingsAndroid,
      iOS: initializationSettingsIOS,
    );
    flutterLocalNotificationsPlugin.initialize(initializationSettings);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Notification App'),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: _showNotification,
          child: Text('Show Notification'),
        ),
      ),
    );
  }

  Future<void> _showNotification() async {
    const androidPlatformChannelSpecifics = AndroidNotificationDetails(
      'your_channel_id',
      'your_channel_name',
      'your_channel_description',
      importance: Importance.max,
      priority: Priority.high,
      showWhen: false,
    );
    const iOSPlatformChannelSpecifics = IOSNotificationDetails();
    const platformChannelSpecifics = NotificationDetails(
      android: androidPlatformChannelSpecifics,
      iOS: iOSPlatformChannelSpecifics,
    );
    await flutterLocalNotificationsPlugin.show(
      0,
      'Hello',
      'This is a test notification',
      platformChannelSpecifics,
    );
  }
}

4. GetX 상태 관리

4.1. 컨트롤러 생성

알림 설정을 관리할 GetX 컨트롤러를 생성합니다. lib/controllers/notification_controller.dart 파일을 생성하고 다음과 같이 작성합니다

import 'package:get/get.dart';

class NotificationController extends GetxController {
  var isNotificationEnabled = false.obs;

  void toggleNotification() {
    isNotificationEnabled.value = !isNotificationEnabled.value;
  }
}

4.2. UI와 컨트롤러 연결

이제 HomeScreen에서 NotificationController를 사용하도록 설정합니다

import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:flutter_local_notifications/flutter_local_notifications.dart';
import 'controllers/notification_controller.dart';

void main() {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return GetMaterialApp(
      title: 'Notification App',
      home: HomeScreen(),
    );
  }
}

class HomeScreen extends StatelessWidget {
  final NotificationController notificationController = Get.put(NotificationController());
  final FlutterLocalNotificationsPlugin flutterLocalNotificationsPlugin = FlutterLocalNotificationsPlugin();

  HomeScreen() {
    final initializationSettingsAndroid = AndroidInitializationSettings('app_icon');
    final initializationSettingsIOS = IOSInitializationSettings();
    final initializationSettings = InitializationSettings(
      android: initializationSettingsAndroid,
      iOS: initializationSettingsIOS,
    );
    flutterLocalNotificationsPlugin.initialize(initializationSettings);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Notification App'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Obx(() => Switch(
                  value: notificationController.isNotificationEnabled.value,
                  onChanged: (value) {
                    notificationController.toggleNotification();
                    if (value) {
                      _showNotification();
                    }
                  },
                )),
            Obx(() => Text(
                  notificationController.isNotificationEnabled.value
                      ? 'Notifications Enabled'
                      : 'Notifications Disabled',
                )),
          ],
        ),
      ),
    );
  }

  Future<void> _showNotification() async {
    const androidPlatformChannelSpecifics = AndroidNotificationDetails(
      'your_channel_id',
      'your_channel_name',
      'your_channel_description',
      importance: Importance.max,
      priority: Priority.high,
      showWhen: false,
    );
    const iOSPlatformChannelSpecifics = IOSNotificationDetails();
    const platformChannelSpecifics = NotificationDetails(
      android: androidPlatformChannelSpecifics,
      iOS: iOSPlatformChannelSpecifics,
    );
    await flutterLocalNotificationsPlugin.show(
      0,
      'Hello',
      'This is a test notification',
      platformChannelSpecifics,
    );
  }
}

5. 알림 설정 저장

사용자가 알림 설정을 변경할 때마다 그 설정을 저장하고 앱 시작 시 불러오는 방법을 추가합니다. 이를 위해 shared_preferences 패키지를 사용합니다.

5.1. pubspec.yaml 파일 업데이트

dependencies:
  flutter:
    sdk: flutter
  get: ^4.6.5
  flutter_local_notifications: ^9.0.0
  shared_preferences: ^2.0.13

5.2. 알림 설정 저장 및 불러오기

NotificationController를 업데이트하여 SharedPreferences를 사용해 설정을 저장하고 불러옵니다

import 'package:get/get.dart';
import 'package:shared_preferences/shared_preferences.dart';

class NotificationController extends GetxController {
  var isNotificationEnabled = false.obs;

  @override
  void onInit() {
    super.onInit();
    _loadNotificationSetting();
  }

  void toggleNotification() {
    isNotificationEnabled.value = !isNotificationEnabled.value;
    _saveNotificationSetting(isNotificationEnabled.value);
  }

  void _loadNotificationSetting() async {
    final prefs = await SharedPreferences.getInstance();
    isNotificationEnabled.value = prefs.getBool('isNotificationEnabled') ?? false;
  }

  void _saveNotificationSetting(bool value) async {
    final prefs = await SharedPreferences.getInstance();
    prefs.setBool('isNotificationEnabled', value);
  }
}

6. 결론

이 가이드에서는 플러터와 GetX를 사용하여 알림 설정을 구현하는 방법을 다루었습니다.

GetX의 상태 관리, 라우팅, 의존성 주입을 통해 효율적으로 알림 설정을 관리할 수 있습니다.

또한, SharedPreferences를 사용하여 사용자 설정을 저장하고 불러오는 방법도 소개했습니다. 이를 통해 사용자는 자신의 알림 설정을 쉽게 관리할 수 있습니다.

 

수발가족을 위한 일기장 “나비일기장”

 

https://play.google.com/store/apps/details?id=com.maccrey.navi_diary_release

 

나비일기장 [수발일기장] - Google Play 앱

수형자 수발가족및 수발인을 위한 일기장으로 수형생활시기에 따른 정보를 얻을 수 있습니다.

play.google.com

 

 

비공개테스트를 위한 20명의 테스터모집 앱 "테스터 쉐어"

 

https://play.google.com/store/apps/details?id=com.maccrey.tester_share_release

 

Tester Share [테스터쉐어] - Google Play 앱

Tester Share로 Google Play 앱 등록을 단순화하세요.

play.google.com

 

반응형