[Flutter] StatefulWidget과 State 클래스

popolarburr·2023년 9월 4일
0
post-thumbnail

StatefulWidget 클래스

  • StatefulWidget 클래스는 위젯의 상태를 관리하고 상태가 변경될 때 알립니다.
  • StatefulWidget은 렌더링되는 부분과 상태를 분리하여 상태 관리를 가능하게 합니다.
  • 주로 StatelessWidget과 함께 사용되며, StatelessWidget은 렌더링된 UI를 정의하고 StatefulWidget은 해당 UI의 상태를 관리합니다.
class CounterApp extends StatefulWidget {
  @override
  _CounterAppState createState() => _CounterAppState();
}

State 클래스

  • State 클래스는 StatefulWidget에 연결되어 해당 위젯의 상태를 저장하고 관리합니다.
  • State 객체는 렌더링된 UI의 상태를 변경하고 이를 화면에 반영하는 역할을 합니다.
  • State 객체는 build 메서드를 구현하여 화면을 정의하고 반환합니다.
class _CounterAppState extends State<CounterApp> {
  int _counter = 0;

  void _incrementCounter() {
    setState(() {
      _counter++;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Counter App'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              '$_counter',
              style: TextStyle(fontSize: 48.0),
            ),
            RaisedButton(
              onPressed: _incrementCounter,
              child: Text('Increment'),
            ),
          ],
        ),
      ),
    );
  }
}

위의 예시에서 CounterApp 클래스는 StatefulWidget로 정의되고, _CounterAppState 클래스는 이에 연결된 State 클래스입니다. _CounterAppState 클래스의 build 메서드는 UI를 정의하며, _counter 변수의 값을 변경하는 _incrementCounter 메서드를 호출할 때 setState 함수를 사용하여 UI 갱신을 요청합니다.

이렇게 StatefulWidget과 State 클래스를 사용하여 위젯의 상태 관리와 UI 표현을 분리함으로써, Flutter 앱은 상태 변경에 따라 동적으로 화면을 업데이트하고 사용자 상호작용을 처리할 수 있습니다.

profile
차곡차곡

0개의 댓글