공log/[Flutter]

[Flutter] 플러터 #23 - Provider

ming_OoO 2023. 5. 26. 21:09
728x90

Provider는 플러터에서 상태 관리를 쉽게 할 수 있도록 도와주는 라이브러리입니다. 이 라이브러리를 사용하면 앱 전역에서 상태를 공유하고 업데이트할 수 있습니다. 다음은 Provider를 사용하여 간단한 카운터 앱의 상태를 관리하는 예시 코드입니다:

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

class CounterModel with ChangeNotifier {
  int _count = 0;

  int get count => _count;

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

class CounterApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ChangeNotifierProvider(
      create: (context) => CounterModel(),
      child: MaterialApp(
        home: Scaffold(
          appBar: AppBar(title: Text('Counter App')),
          body: Center(
            child: Consumer<CounterModel>(
              builder: (context, counter, child) {
                return Text('Count: ${counter.count}');
              },
            ),
          ),
          floatingActionButton: FloatingActionButton(
            onPressed: () {
              Provider.of<CounterModel>(context, listen: false).increment();
            },
            child: Icon(Icons.add),
          ),
        ),
      ),
    );
  }
}

이 예시 코드에서는 CounterModel 클래스가 상태를 관리하고, CounterApp 위젯에서 ChangeNotifierProvider를 사용하여 상태를 공유합니다. Consumer 위젯은 상태가 업데이트될 때마다 해당 부분을 다시 렌더링합니다. floatingActionButton을 누를 때마다 CounterModelincrement 메서드가 호출되어 카운터가 증가하고 UI가 업데이트됩니다.

 

 

728x90