StatelessWidget
말 그대로 상태가 없는 위젯 클래스다
먼저 sample앱에서 카운터 앱을 보여주는 MyHomePage를 stateless로 바꿔서 예제로 본다
class MyHomePage extends StatelessWidget {
int count = 0;
MyHomePage({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$count',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
//화면 우측 하단에 있는 버튼
floatingActionButton: FloatingActionButton(
onPressed: () {
count++;
},
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
원래 stateful위젯에서는 우측 하단의 floatingActionButton을 누르면 화면에 0이 1씩 증가하는 게 보이지만
위 코드처럼 stateless위젯이라면 눌러도 바뀌지 않는다
이유는 stateless는 상태가 없는 위젯이기 때문이다
count 변수의 상태가 없으므로 위젯에 반영이되지않는다
StatelessWidget 정리
- 상태가 없는 위젯
- 위젯들의 변화가 필요 없는 화면을 구성할 때 사용하는 클래스
StatefulWidget
StatelessWidget과 반대로 상태가 있는 위젯
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key}) : super(key: key);
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int count = 0;
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
const Text(
'You have pushed the button this many times:',
),
Text(
'$count',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
//화면 우측 하단에 있는 버튼
floatingActionButton: FloatingActionButton(
onPressed: () {
setState(() {
count++;
});
},
tooltip: 'Increment',
child: const Icon(Icons.add),
),
);
}
}
위 코드처럼 stateful로 변경해주면 상태가 있는 위젯이고 onPressed에서 setState로 카운터 상태 값을 늘려주기 때문에 화면에 바로바로 1씩 늘어가는 게 적용돼서 보인다
여기서 setstate는 상태를 갱신해 화면에 다시 보여준다. 즉 변경된 값을 위젯에 반영하는 메서드이다
StatefulWidget 정리
- 상태가 있는 위젯
- 위젯들의 변화가 필요한 화면을 구성할 때 사용하는 클래스
- setState를 사용하여 build() 메서드를 호출하여 상태 변경
'Flutter' 카테고리의 다른 글
Flutter - fontFamily 적용 (0) | 2022.01.02 |
---|---|
Flutter-text위젯 (0) | 2022.01.02 |
Flutter sample 앱 분석(counter app) (0) | 2021.12.29 |
Flutter 프로젝트 생성 (0) | 2021.12.29 |
Flutter 개발 환경 구축(windows) (0) | 2021.12.29 |