[flutter] 플러터에서의 상태 관리 라이브러리 소개

플러터(Flutter)는 Google에서 개발한 모바일 애플리케이션 개발 프레임워크로, 효율적이고 강력한 상태 관리가 필요합니다. 이러한 상태 관리를 도와주는 다양한 라이브러리들이 있지만, 그 중에서도 몇 가지 인기 있는 라이브러리를 소개하고자 합니다.

Provider

Provider는 플러터에서 상태 관리를 위한 가장 보편적인 라이브러리입니다. Provider는 단순하고 직관적인 API를 제공하여 간단한 상태 관리부터 복잡한 내부 의존성 관리까지 다양한 상황을 다룰 수 있습니다. 상태값을 제공하고 사용하는 모델을 만들어 상태 변화를 감지하고 업데이트하는 방식으로 동작합니다.

import 'package:flutter/material.dart';
import 'package:provider/provider.dart';

void main() {
  runApp(
    ChangeNotifierProvider(
      create: (context) => MyModel(),
      child: MyApp(),
    ),
  );
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'My App',
      home: Scaffold(
        appBar: AppBar(
          title: Text('My App'),
        ),
        body: Center(
          child: Consumer<MyModel>(
            builder: (context, myModel, child) {
              return Text(myModel.myValue.toString());
            },
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            Provider.of<MyModel>(context, listen: false).increment();
          },
          child: Icon(Icons.add),
        ),
      ),
    );
  }
}

class MyModel with ChangeNotifier {
  int _myValue = 0;
  int get myValue => _myValue;

  void increment() {
    _myValue++;
    notifyListeners();
  }
}

MobX

MobX는 플러터 상태 관리를 위한 또 다른 인기 있는 라이브러리입니다. MobX는 애노테이션 기반으로 동작하여, 컴파일 타임에 코드 생성을 통해 상태 변화를 추적하고 자동으로 업데이트합니다. 이를 통해 효율적인 상태 관리가 가능해집니다.

import 'package:flutter/material.dart';
import 'package:mobx/mobx.dart';
part 'my_model.g.dart';

void main() async {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  final MyModel myModel = MyModel();

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'My App',
      home: Scaffold(
        appBar: AppBar(
          title: Text('My App'),
        ),
        body: Center(
          child: Observer(
            builder: (context) {
              return Text(myModel.myValue.toString());
            },
          ),
        ),
        floatingActionButton: FloatingActionButton(
          onPressed: () {
            myModel.increment();
          },
          child: Icon(Icons.add),
        ),
      ),
    );
  }
}

class MyModel = _MyModel with _$MyModel;

abstract class _MyModel with Store {
  @observable
  int myValue = 0;

  @action
  void increment() {
    myValue++;
  }
}

Redux

Redux는 플러터에서의 상태 관리를 위해 널리 사용되는 라이브러리입니다. Redux는 단방향 데이터 플로우 개념을 기반으로 하여, 애플리케이션의 상태를 불변의 객체로 관리하고 상태 변화를 액션으로 전달하여 업데이트합니다. Redux는 상태의 변화를 예측 가능하게 만들어, 디버깅과 테스트를 용이하게 합니다.

import 'package:flutter/material.dart';
import 'package:redux/redux.dart';
import 'package:flutter_redux/flutter_redux.dart';

void main() {
  final store = Store<int>(
    reducer,
    initialState: 0,
  );

  runApp(MyApp(store: store));
}

class MyApp extends StatelessWidget {
  final Store<int> store;

  MyApp({required this.store});

  @override
  Widget build(BuildContext context) {
    return StoreProvider<int>(
      store: store,
      child: MaterialApp(
        title: 'My App',
        home: Scaffold(
          appBar: AppBar(
            title: Text('My App'),
          ),
          body: StoreConnector<int, int>(
            converter: (store) => store.state,
            builder: (context, count) {
              return Center(
                child: Text(count.toString()),
              );
            },
          ),
          floatingActionButton: StoreConnector<int, VoidCallback>(
            converter: (store) {
              return () => store.dispatch(Action.increment);
            },
            builder: (context, callback) {
              return FloatingActionButton(
                onPressed: callback,
                child: Icon(Icons.add),
              );
            },
          ),
        ),
      ),
    );
  }
}

enum Action { increment }

int reducer(int state, dynamic action) {
  if (action == Action.increment) {
    return state + 1;
  }
  return state;
}

위에서 소개한 Provider, MobX, Redux는 플러터에서 상태 관리를 위해 널리 사용되는 라이브러리 중 일부입니다. 각각의 라이브러리는 다른 특징과 장단점을 가지고 있으므로, 프로젝트에 맞게 선택하여 사용하면 됩니다. 해당 라이브러리의 공식 문서와 다른 개발자들의 리뷰를 참고하여 적절한 상태 관리 방법을 선택해보세요.

참고 자료