ChangeNotifier

샤워실의 바보·2024년 2월 16일
0
post-thumbnail

ChangeNotifier는 Flutter에서 상태 관리를 위한 간단하고 효율적인 방법을 제공하는 클래스입니다. 이 클래스는 Listenable 인터페이스를 구현합니다. ChangeNotifier를 사용하면 데이터의 변경을 감지하고, 데이터가 변경될 때마다 리스너(예: 위젯)에게 알릴 수 있습니다. 이를 통해 앱의 다른 부분들이 상태 변화에 반응하여 업데이트 될 수 있게 합니다.

기본 사용 방법

  1. 상태 정의: 상태를 가지고 있는 클래스를 ChangeNotifier를 상속받아 정의합니다. 이 클래스 내에서 관리하고자 하는 변수들을 선언합니다.
  2. 상태 업데이트: 상태를 변경하는 메서드 내에서 notifyListeners() 메서드를 호출하여, 리스너들(상태를 사용하는 위젯들)에게 상태 변경을 알립니다.
  3. 상태 사용: ChangeNotifierProvider (Provider 패키지를 사용하는 경우) 또는 다른 상태 관리 방법을 통해 상태를 앱에 제공하고, Consumer 위젯이나 context.watch(), context.read() 메서드를 사용하여 상태를 읽습니다.

예시

아래는 ChangeNotifier를 사용하여 비디오 음소거 상태를 관리하는 간단한 예시입니다.

import 'package:flutter/material.dart';

// VideoConfig는 ChangeNotifier를 상속받아 비디오 설정을 관리하는 클래스입니다.
class VideoConfig extends ChangeNotifier {
  bool autoMute = false; // autoMute 상태를 저장하는 변수입니다.

  // autoMute 상태를 토글하는 메서드입니다.
  void toggleAutoMute() {
    autoMute = !autoMute; // 상태를 반전시킵니다.
    notifyListeners(); // 리스너들에게 상태 변경을 알립니다.
  }
}

이 클래스를 사용하여 상태를 관리하는 방법은 다음과 같습니다.

  1. 상태 제공: 앱의 최상위에 상태를 제공합니다. Provider 패키지를 사용하면 ChangeNotifierProvider를 사용하여 앱의 최상위에 VideoConfig 인스턴스를 제공할 수 있습니다.
  2. 상태 사용: 상태를 사용하고자 하는 위젯에서 Consumer<VideoConfig> 위젯을 사용하거나, context.watch()를 통해 autoMute 상태를 구독하고 UI를 해당 상태에 따라 업데이트 할 수 있습니다.

ChangeNotifier는 간단한 상태 관리가 필요할 때 매우 유용하며, 특히 Provider 패키지와 함께 사용할 때 Flutter 앱에서 상태 관리를 쉽게 할 수 있게 해줍니다.

VideoConfig 클래스

import 'package:flutter/widgets.dart';

// VideoConfig 클래스는 ChangeNotifier를 확장하여, autoMute 상태 변경 시 리스너들에게 알림을 보낼 수 있습니다.
class VideoConfig extends ChangeNotifier {
  // autoMute 변수는 비디오가 자동으로 음소거 될지 여부를 결정합니다.
  bool autoMute = false;

  // toggleAutoMute 메소드는 autoMute 상태를 토글하고, 변경 사항을 구독자들에게 알립니다.
  void toggleAutoMute() {
    autoMute = !autoMute;
    notifyListeners(); // 상태 변경을 알림.
  }
}

// VideoConfig의 인스턴스를 생성합니다. 앱 전체에서 공유될 수 있습니다.
final videoConfig = VideoConfig();

SettingsScreen 클래스

import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:font_awesome_flutter/font_awesome_flutter.dart';

// SettingsScreen은 앱의 설정을 관리하는 화면입니다.
class SettingsScreen extends StatefulWidget {
  const SettingsScreen({super.key});

  
  State<SettingsScreen> createState() => _SettingsScreenState();
}

class _SettingsScreenState extends State<SettingsScreen> {
  // _notifications 변수는 알림 설정의 상태를 관리합니다.
  bool _notifications = false;

  // _onNotificationsChanged 메소드는 사용자가 알림 설정을 변경할 때 호출됩니다.
  void _onNotificationsChanged(bool? newValue) {
    if (newValue == null) return;
    setState(() {
      _notifications = newValue;
    });
  }

  
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Settings'),
      ),
      body: ListView(
        children: [
          // AnimatedBuilder를 사용하여 videoConfig의 변화를 감지하고 UI를 업데이트 합니다.
          AnimatedBuilder(
            animation: videoConfig,
            builder: (context, child) => SwitchListTile.adaptive(
              value: videoConfig.autoMute,
              onChanged: (value) {
                videoConfig.toggleAutoMute(); // autoMute 상태를 토글합니다.
              },
              title: const Text("Mute video"),
              subtitle: const Text("Videos will be muted by default."),
            ),
          ),
          // 기타 설정 관련 UI 요소들...
        ],
      ),
    );
  }
}

VideoConfig 클래스는 ChangeNotifier를 확장하여 비디오의 자동 음소거 설정을 관리합니다. 이 클래스는 autoMute 상태를 토글하는 메소드를 제공하며, 상태가 변경될 때마다 notifyListeners를 호출하여 모든 리스너(예: UI 위젯)에게 상태 변경을 알립니다.

SettingsScreen 위젯에서는 AnimatedBuilder를 사용하여 videoConfig 객체의 변화를 감지하고, 이를 통해 비디오의 자동 음소거 설정을 사용자가 변경할 수 있도록 합니다. 이 예제는 Flutter에서 ChangeNotifier를 활용하여 앱의 상태 관리를 구현하는 방법을 보여줍니다.

profile
공부하는 개발자

0개의 댓글