Flutter StatefulWidget


Flutter에서 `StatefulWidget`은 상태를 가지며, 그 상태가 변경될 때 UI를 다시 빌드할 수 있는 위젯입니다. 반면에 `StatelessWidget`은 상태가 없는 위젯으로, 생성된 후에는 변하지 않습니다. `StatefulWidget`은 상태가 변경될 수 있는 애플리케이션의 인터페이스 요소를 만들 때 사용됩니다.

`StatefulWidget`은 두 개의 클래스가 필요합니다:
1. `StatefulWidget` 클래스 자체.
2. `State` 클래스를 확장하는 상태 클래스.

`StatefulWidget` 클래스는 위젯의 틀만 제공하고, `State` 클래스는 실제 상태를 관리하고 빌드 메서드를 통해 UI를 렌더링합니다.

### 예제 코드

간단한 `StatefulWidget` 예제를 통해 설명해보겠습니다. 이 예제는 버튼을 눌러 카운터를 증가시키는 간단한 애플리케이션입니다.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  int _counter = 0;

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('StatefulWidget Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(
              'You have pushed the button this many times:',
            ),
            Text(
              '$_counter',
              style: Theme.of(context).textTheme.headline4,
            ),
          ],
        ),
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: _incrementCounter,
        tooltip: 'Increment',
        child: Icon(Icons.add),
      ),
    );
  }
}



### 코드 설명

1. **MyHomePage 클래스 (StatefulWidget)**:
   – `MyHomePage`는 `StatefulWidget`을 상속합니다.
   – `createState` 메서드는 이 위젯의 상태를 관리하는 `_MyHomePageState` 객체를 생성합니다.

2. **_MyHomePageState 클래스 (State)**:
   – `_MyHomePageState`는 `State<MyHomePage>`를 상속합니다.
   – `_counter` 변수는 상태를 저장합니다.
   – `_incrementCounter` 메서드는 `_counter`를 증가시키고 `setState`를 호출하여 UI를 업데이트합니다.
   – `build` 메서드는 UI를 정의하며, `_counter` 값이 변경될 때마다 다시 호출됩니다.

### `setState` 메서드

`setState` 메서드는 상태를 변경하고, 변경된 상태를 기반으로 UI를 다시 빌드합니다. 상태를 변경할 때마다 반드시 `setState`를 호출해야 UI가 업데이트됩니다.

이와 같은 구조를 통해 Flutter는 상태 관리와 UI 업데이트를 효율적으로 처리합니다. `StatefulWidget`과 `State`의 분리된 구조는 복잡한 애플리케이션에서도 상태와 UI의 관리를 용이하게 합니다.


Leave a Reply

Your email address will not be published. Required fields are marked *