컨테이너

[Flutter] StatelessWidget과 StatefulWidget의 차이점 본문

Development/Flutter

[Flutter] StatelessWidget과 StatefulWidget의 차이점

어항 2021. 1. 18. 21:48
반응형

플러터의 모든 UI는 위젯으로 구현됩니다.

이렇게 UI를 구성하는 위젯의 class는 두 가지가 있습니다.

 

 

StatelessWidget    |    StatefulWidget

 


 

StatelessWidget

(상태를 가지지 않는 위젯)

 

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  int count = 0;
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'StatelessWidget',
      home: Scaffold(
        appBar: AppBar(
          title: Text("StatelessWidget"),
          centerTitle: true,
        ),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text("$count"),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                FloatingActionButton(
                    onPressed: () {
                      count--;
                      print("count: $count");
                    },
                    child: Text('-')),
                FloatingActionButton(
                    onPressed: () {
                      count++;
                      print("count: $count");
                    },
                    child: Text('+'))
              ],
            )
          ],
        ),
      ),
    );
  }
}

 

화면을 구성하는 UI는 build 메서드가 호출되면서 만들어집니다.

StatelessWidget에서는 build 메서드를 화면이 생성될 때 한번만 호출합니다.

 

즉, 처음 화면이 생성된 후 사용하고 있는 변수의 값이 변경되어도

build 메서드를 호출하지 않기 때문에 값의 변화를 화면에서 확인할 수 없습니다.

 

이해를 돕기위해 위 예제 코드를 직접 실행시켜 확인해볼까요?

 

 

 

위 화면에서 + 버튼을 클릭해도 화면에서의 count 값은 0에서 변하지 않습니다.

그렇다면 실제 count의 값이 변하지 않아 화면의 값이 바뀌지 않는 걸까요?

 

Restarted application in 743ms.
I/flutter (27373): count: 1
I/flutter (27373): count: 2
I/flutter (27373): count: 3
I/flutter (27373): count: 4
I/flutter (27373): count: 5
I/flutter (27373): count: 6

 

확인해보면 count의 값은 + 버튼을 누를 때마다 증가하고 있습니다.

슬슬 감이 오시나요?

 

UI를 변화시키기 위해선 build 메서드의 호출이 필요합니다.

 

하지만, StatelessWidget에서는 build 메서드가 첫 화면을 구현할 때만 호출되므로

아무리 + 버튼을 클릭해도 count의 값 변화를 화면에서 확인할 수 없습니다.

 

그렇다면 StatefulWidget은 어떨까요?

 

 

 


 

StatefulWidget

(상태를 가지는 위젯)

 

 

import 'package:flutter/material.dart';

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

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  int count = 0;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'StatefulWidget',
      home: Scaffold(
        appBar: AppBar(
          title: Text("StatefulWidget"),
          centerTitle: true,
        ),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              "$count",
              style: TextStyle(fontSize: 80),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                FloatingActionButton(
                    onPressed: () {
                      setState(() {
                        count--;
                        print("count: $count");
                      });
                    },
                    child: Text('-')),
                FloatingActionButton(
                    onPressed: () {
                      setState(() {
                        count++;
                        print("count: $count");
                      });
                    },
                    child: Text('+'))
              ],
            )
          ],
        ),
      ),
    );
  }
}

 

StatefulWidget에서는 setState() 사용해 필요에 따라 build 메서드를 호출할 수 있습니다.

 

위 예제코드를 잠시 살펴볼까요?

 

setState(() {
    count++;
    print("count: $count");
});

 

+ 버튼을 클릭 시 count의 값이 1 증가합니다.

그리고 1이 증가된 count의 값을 print 합니다.

 

마지막으로 build 메서드를 호출합니다.

 

이러한 과정을 통해 여러분들은 count의 증감된 값을 화면에서 확인할 수 있습니다.

 

 

Restarted application in 625ms.
I/flutter (27373): count: 1
I/flutter (27373): count: 2
I/flutter (27373): count: 3
I/flutter (27373): count: 4
I/flutter (27373): count: 5
I/flutter (27373): count: 6

 

 

 

경우에 따라 여러분들이 원하는 class를 사용해 UI를 구현하시면 됩니다.

 

 

 

 

반응형

'Development > Flutter' 카테고리의 다른 글

[Flutter] SizedBox Class  (0) 2021.01.19
[Flutter] Row, Column Class  (0) 2021.01.19
[Flutter] MaterialApp Class  (0) 2021.01.19
[Flutter] Kakao Map 사용하기  (4) 2020.12.27
[Flutter] StatusBar(상태바) 디자인, 숨기기  (0) 2020.12.22
Comments