-
[FLUTTER] StatelessWidget & StatefulWidgetFlutter 2023. 3. 23. 16:36
[StatelessWidget]
상태 변화가 없어 화면을 새로고침 할 필요가 없는 위젯
/// Copyright 2022. ⓒ DevStory.co.kr All rights reserved. import 'package:flutter/material.dart'; // Material 위젯 가져오기 void main() { print("1. 시작"); runApp(const MyApp()); // MyApp 위젯으로 Flutter 시작! } class MyApp extends StatelessWidget { const MyApp({Key? key}) : super(key: key); @override Widget build(BuildContext context) { print("2. build 호출 됨"); // 화면에 보여지는 영역 return const MaterialApp( home: Scaffold( body: Center( child: Text( "hello Stateless Widget", style: TextStyle(fontSize: 35), ), ), ), ); } }
- extends StatelessWidget : StatelessWidget의 기능을 물려받음
- 생성자 : 클래스 이름과 동일한 함수
- build 함수 : 화면에 보여줄 자식 위젯을 반환하는 함수
해당 함수를 상속받을 경우 무조건 build 함수를 만들어줘야한다.
override : 해당 함수를 "덮어씌우겠다"라는 의미
화면에 보이는 첫 번째 위젯은 일반적으로 MaterialApp 또는 CupertinoApp 위젯으로 시작한다.
[StatefulWidget]
상태 변화가 있어 화면을 새로고침 할 필요가 있는 위젯
기본적으로 2개의 클래스로 구성되어 있음!
- MyApp : StatefulWidget의 기능을 물려받 클래스
- _MyAppState : MyApp 상태를 가진 클래스(실질적인 내용은 여기에 들어감)
/// Copyright 2022. ⓒ DevStory.co.kr All rights reserved. // ignore_for_file: prefer_const_constructors import 'package:flutter/material.dart'; // Material 위젯 가져오기 void main() { print("1. 시작"); runApp(const MyApp()); // MyApp 위젯으로 Flutter 시작! } // StatefulWidget의 기능을 물려받음 class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key); @override State<MyApp> createState() => _MyAppState(); // 2개의 클래스를 연결해주는 함수 (MyApp이랑 _MyAppState를 연결) } // MyApp의 상태를 나타내는 클래스 class _MyAppState extends State<MyApp> { int number = 1; // number가 1인 상태 @override Widget build(BuildContext context) { print("2. build 호출 됨"); return MaterialApp( home: Scaffold( body: Center( child: Text("$number", style: TextStyle(fontSize: 35)), // 화면에 보여지는 숫자 ), floatingActionButton: FloatingActionButton( // 버튼 누르면 실행됨 child: Icon(Icons.add), onPressed: () { print("3. 클릭 됨"); // setState : build 메소드를 다시 호출해서 화면 갱신! setState(() { // 새로고침 number += 1; // number를 1만큼 증가 }); }, ), ), ); } }
우측하단의 버튼을 클릭할때마다 숫자 증가
- 35번째 print("3. 클릭 됨"); 출력
- 39번째 number 1 증가
- 38번째 라인의 setState로 인해 화면 갱신 (= build 함수 호출)
- build 함수가 호출되어 25번째 print("2. build 호출 됨"); 출력
StatefulWidget 위젯에서 setState()를 호출하면 build() 함수가 다시 실행되면서 화면이 갱신된다!
'Flutter' 카테고리의 다른 글
[FLUTTER] Stack (0) 2023.03.23 [FLUTTER] Column & Row (0) 2023.03.23 [FLUTTER] Image & SingleChildScrollView (0) 2023.03.14 [FLUTTER] Container (margin & padding & alignment / boxDecoration) (0) 2023.03.14 [FLUTTER] AppBar & Padding (0) 2023.03.14