관리 메뉴

Bull

[Flutter::Widget] StatefulBuilder 본문

Software Framework/Flutter

[Flutter::Widget] StatefulBuilder

Bull_ 2024. 8. 27. 10:53

https://api.flutter.dev/flutter/widgets/StatefulBuilder-class.html

 

StatefulBuilder class - widgets library - Dart API

A platonic widget that both has state and calls a closure to obtain its child widget. The StateSetter function passed to the builder is used to invoke a rebuild instead of a typical State's State.setState. Since the builder is re-invoked when the StateSett

api.flutter.dev

 

StatefulBuilder는 특정 부분의 위젯 트리 내에서 상태를 관리할 수 있도록 돕는 위젯이다. 전체 위젯에 대한 상태 관리를 제공하지만, 때로는 모달 다이얼로그바텀 시트 등의 소규모 구성 요소 내에서만 상태를 업데이트하고 싶을 때가 있다. 이러한 경우 StatefulBuilder를 사용하면, 상태 변경이 필요한 특정 부분만을 위한 로컬 상태를 생성하고 관리할 수 있다.

showModalBottomSheet(
  context: context,
  builder: (BuildContext context) {
    int counter = 0;

    return StatefulBuilder(
      builder: (BuildContext context, StateSetter setState) {
        return Container(
          padding: EdgeInsets.all(20),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: <Widget>[
              Text('Counter: $counter'),
              ElevatedButton(
                onPressed: () {
                  setState(() {
                    counter++;
                  });
                },
                child: Text('Increment'),
              ),
            ],
          ),
        );
      },
    );
  },
);