본문 바로가기
Language_/Flutter

[Flutter] StatelessWidget & StatefulWidget 차이점 정리

by 낭람_ 2020. 9. 26.
반응형

Flutter의 Widget은 StatelessWidget(SLW)과 StatefulWidget(SFW)을 상속받아서 만들 수 있다.

 

또한, 두 위젯은 Scaffold를 이용해 동일한 방식으로 화면을 구성하게 된다.

 

StatelessWidget은 단 한번만 Build를 한다. 한번 그려진 화면은 계속 유지되며, 성능상 장점이 생긴다.

 

StatefulWidget은 state를 포함하며, setState가 발생할때마다 Build과정이 일어나고, 동적 화면을 쉽게 구현이 가능하다.

 

밑의 예제를 보고 차이점을 확실하게 알아가자.

 

import 'package:flutter/material.dart';

void main() => runApp(SLWApp());

class SLWApp extends StatelessWidget {
  int _count = 0;
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'SLW',
      home: Scaffold(
        appBar: AppBar(
          title: Text('StatelessWidget App'),
        ),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              "$_count",
              style: TextStyle(fontSize: 30),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                RaisedButton(
                    onPressed: () {
                      _count--;
                      print("value of count = $_count");
                    },
                    child: Text('-')),
                RaisedButton(
                    onPressed: () {
                      _count++;
                      print("value of count = $_count");
                    },
                    child: Text('+'))
              ],
            )
          ],
        ),
      ),
    );
  }
}

 

이 코드는 StatelessWidget으로 만들었다.

 

0

I/flutter (12980): value of count = 1
I/flutter (12980): value of count = 2
I/flutter (12980): value of count = 3
I/flutter (12980): value of count = 4
I/flutter (12980): value of count = 5
I/flutter (12980): value of count = 6

 

버튼을 누르면 VScode에서는 저렇게 count가 올라가지만, 실제 앱에서는 count가 올라가지 않는다..

 

그럼 StatefulWidget의 경우에는 어떨까?

 

import 'package:flutter/material.dart';

void main() => runApp(SFWApp());

class SFWApp extends StatefulWidget {
  @override
  _SFWApp createState() => _SFWApp();
}

class _SFWApp extends State<SFWApp> {
  int _count = 0;
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'SLW',
      home: Scaffold(
        appBar: AppBar(
          title: Text('StatefulWidget App'),
        ),
        body: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text(
              "$_count",
              style: TextStyle(fontSize: 30),
            ),
            Row(
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                RaisedButton(
                    onPressed: () {
                      setState(() {
                        _count--;
                      });
                      print("value of count = $_count");
                    },
                    child: Text('-')),
                RaisedButton(
                    onPressed: () {
                      setState(() {
                        _count++;
                      });
                      print("value of count = $_count");
                    },
                    child: Text('+'))
              ],
            )
          ],
        ),
      ),
    );
  }
}

 

StatelessWidget과 같은 코드지만 StatefulWidget형태로 만들었다.

 

children: [
    RaisedButton(
        onPressed: () {
            setState(() {
                _count--;
            });
            print("value of count = $_count");
        },
        child: Text('-')),
    RaisedButton(
        onPressed: () {
            setState(() {
                _count++;
            });
            print("value of count = $_count");
        },
        child: Text('+'))
],

 

또한 onPressd 부분을 보면 setState가 추가 되었다.

 

setState가 호출될때마다 build를 하기 때문에 count가 올라가면서 화면도 갱신 되는 것이다.

 

0

I/flutter (12980): value of count = 1
I/flutter (12980): value of count = 2
I/flutter (12980): value of count = 3
I/flutter (12980): value of count = 4
I/flutter (12980): value of count = 5

 

count가 잘 올라가는것을 확인 할 수 있다. 

 

StatelessWidget은 단 한번만 Build를 한다. 한번 그려진 화면은 계속 유지되며, 성능상 장점이 생긴다.

 

StatefulWidget은 state를 포함하며, setState가 발생할때마다 Build과정이 일어나고, 동적 화면을 쉽게 구현이 가능하다.

반응형

댓글