Flutter
Stateful Widget
임공부중
2023. 2. 18. 23:19
반응형
Stateless Widget - build 메소드로 UI 출력 * Stateless Widget 에 alt enter 해서 Stateful Widget으로 바꿔주기
Stateful Widget - 위젯에 데이터를 저장하고 데이터의 변화감지 되면 새로고침해서 출력
1. 상태가 없는 위젯 그자체
2. 위젯의 상태에 데이터와 UI를 넣음
void main() {
runApp(MyApp());
}
class MyApp extends StatefulWidget { // 1. 위젯 그자체
@override
State<MyApp> createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> { // 2. 데이터와 UI를 넣는 stateful Widget
// 앱의 root임 두가지 옵션중 하나를 return해야함 1. material 앱(구글)2 cupertino(애플)
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: const Color(0xFFF4EDDB),
body: Container(),
),
);
}
}
# setState
setState(); 함수를 통해서 state에게 새로운 데이터가 있음을 알려줌.
데이터의 변화를 무조건 setState 안에 넣어야한다는 것은 아님.
class _MyAppState extends State<MyApp> {
int counter = 0;
void onClicked(){
setState(() {
counter++;
});
}
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
backgroundColor: const Color(0xFFF4EDDB),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text('Click Count',style: TextStyle(
fontSize: 30,
),),
Text('$counter',style: TextStyle(
fontSize: 30,
),),
IconButton(onPressed: onClicked, icon: const Icon(Icons.add_box_outlined))
],
),
),
),
);
}
}
# BuildContext - 위젯 트리 안에서 위젯의 위치를 다룸
build(BuildContext context) 는 모든 상위 요소들에 대한 정보에 접근할 수 있게 한다.
MyLargeTitle 위젯이 상위 요소인 Theme에 접근
class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
textTheme: TextTheme(
titleLarge: TextStyle(
color: Colors.red,
),
),
),
home: Scaffold(
backgroundColor: const Color(0xFFF4EDDB),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
MyLargeTitle(),
],
),
),
),
);
}
}
class MyLargeTitle extends StatelessWidget {
const MyLargeTitle({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) { // context는 Text 이전에 있는 모든 상위 요소들에 대한 정보
return Text('My Large Title',style: TextStyle(
fontSize: 30, color: Theme.of(context).textTheme.titleLarge!.color,),);
}
}
<null safety>
! 느낌표로 titleLarge가 분명히 있다는 것을 알려줘야한다.
또는 ? 물음표를 이용해서 있으면 사용하라는 것을 알려줘도 됨. titleLarge?.color
# Widget Lifecycle
stateful Widget 의 함수
- initState() // 변수를 초기화하는 메소드, build 메소드 보다 앞에 쓰여서 먼저 실행된다.
- dispose() // 위젯이 스크린에서 제거될 때 호출 되는 메소드
- build() // UI 출력
반응형