Professional Documents
Culture Documents
HTML 은 모든 것이 Element 인 것 처럼
Flutter 에서는 모든 것이 Widget 이다 .
08-1 화면을 구성하는 위젯
vsCode 로 입력 실습
몇 개의 위젯이 있는가 ?
08-1 화면을 구성하는 위젯
MaterialApp: 머티리얼 디자인 적용
Scaffold: 화면 구조 설계
AppBar: 화면 위쪽 앱바 구성
Text: 앱바의 제목
Center: 가운데 정렬
GestureDetector: 사용자 이벤트 처리
Text: 본문에 문자열 출력
위젯은 불변이다
객체를 생성한 후 상태를 바꿀 수 없습니다 .
화면을 새 데이터로 갱신하려면 새로운 위젯 객체를 만들어야 합니다 .
08-2 위젯 트리 알아보기
위젯의 트리 구조
화면은 위젯을 여러 개 조합해서 구성
08-2 위젯 트리 알아보기
화면을 구성하는 3 개의 트리 구조
위젯 트리 , 엘리먼트 트리 element tree 와 렌더 트리 render tree
엘리먼트 트리는 ComponentElement 와 RenderObjectElement 객체로 구성 Widget Tree 는 HTML
Component Element 객체는 트리 구조에서 다른 객체를 포함하는 역할 의 무엇과 비슷한가 ?
실제 화면에 출력할 정보는 RenderObjectElement
08-2 위젯 트리 알아보기
화면을 구성하는 3 개의 트리 구조
허무하죠 ?
정적인 화면 만들기
샘플 코드 실행하는 방법
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text('Stateless Test'),
),
body: const MyStatefulWidget()));
}
}
@override
State<MyStatefulWidget> createState() => _MyStatefulWidgetState();
}
void changeCheck() {
setState(() {
if (enabled) {
stateText = "disable";
enabled = false;
} else {
stateText = "enable";
enabled = true;
}
});
}
@override
Widget build(BuildContext context) {
return Center(
1. 8.3 을 복사해서 실행
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
IconButton(
icon: (enabled
? const Icon(
Icons.check_box,
size: 20,
)
: const Icon(
Icons.check_box_outline_blank,
size: 20,
)),
color: Colors.red,
onPressed: changeCheck,
),
Container(
padding: const EdgeInsets.only(left: 16),
child: Text(
2. 수정
stateText,
style: const TextStyle(fontSize: 30, fontWeight: FontWeight.bold),
),
),
],
),
);
}
}
- Snippet 으로 stateful 을 생성
- 변경되는 속성 및 메소드를 이동
- 메소드를 setState 로 감싼다 .
08-5 상태의 생명주기 매우 중요 !!
부모에
의해
다시
그려질때
08-5 상태의 생명주기
initState() 함수 호출 시점
initState() 함수는 State 객체가 생성되자마자 가장 먼저 최초에 한 번 호출
When the Stateful widget is created, this function is called only once and used to initialize the state.
didChangeDependencies() 함수 호출 시점
didChangeDependencies() 함수는 initState() 함수가 호출된 후에 이어서 호출
상위 위젯의 상태 데이터가 변경될 때 하위 위젯의 didChangeDependencies() 가 자동으로 호출되어
이 함수에서 상위 위젯의 변경된 상태 데이터를 이용 x
if you use InheritedWidget or Provider, when the InheritedWidget or Provider value is changed,
this function is called again.
Dependency 라는 것은 Provider 에 대한 의존을 의미
didUpdateWidget() 함수 호출 시점
State 에서는 자신과 연결된 StatefulWidget 이 다시 생성되는 순간을 감지 x
부모 위젯이 변경되어 다시 그려져야 하는 경우 0
08-5 상태의 생명주기 deactivate()
• The deactivate function is called when the
build() 함수 호출 시점 state object is removed on the tree.
• Sometimes, Flutter deletes the state ob-
ject and add it again.
최초 호출
• For example, when you move the widget
setState() 함수에 의해 호출 to the some other place of the widget tree
didUpdateWidget() 함수에 의해 호출 by GlobalKey, so the deactivate function is
executed when the state object is re-
dispose() 함수 호출 시점 moved.
모든 위젯은 키 값을 가질 수 있습니다 .
• 추천 방법 :
그냥 신경쓰지 말고 코딩할 것
Quick fix 에서 제안하는 대로 key 를 추가 할 것
VS Code 에서는 Stateless Widget 도 무조건 key 를 설정하는 것을 추천
다음 코드를 분석하고 이번 장을 종료
이후 설명은 key 을 제거하면 동작이 제대로 되지 않음을 보여준다 .
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
List<Widget> widgetList = [
List<Widget> widgetList = [
MyColorItemWidget(
Colors.red,
key: UniqueKey(),
),
MyColorItemWidget(Colors.blue, key: UniqueKey()),
];
MyColorItemWidget(
onChange() {
print(widgetList.elementAt(0).key);
setState(() {
widgetList.insert(1, widgetList.removeAt(0));
});
}
Colors.red,
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Key Test'),
),
body: Column(children: [
key: UniqueKey(),
Row(
children: widgetList,
),
ElevatedButton(onPressed: onChange, child: Text("toggle"))
]));
}
}
),
class MyColorItemWidget extends StatefulWidget {
Color color;
MyColorItemWidget(this.color, {Key? key}) : super(key: key);
@override
State<StatefulWidget> createState() {
return _MyColorItemWidgetState(color);
ValueKey: 문자열 , 숫자 키값
ObjectKey: 객체 키값
UniqueKey: 유일한 난수 키값
08-6 BuildContext 객체와 위젯 키
키 클래스
위젯 키 활용하기
감사합니다
단단히 마음먹고 떠난 사람은
산꼭대기에 도착할 수 있다 .
산은 올라가는 사람에게만 정복된다 .
윌리엄 셰익스피어
William Shakespeare