import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
// 앱의 시작점, 상태를 가질 수 없는 위젯
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
// MaterialApp을 감싼 MyListWidget을 home 화면으로 설정
return MaterialApp(home: MyListWidget());
}
}
// 앱의 메인 화면, 상태 변경이 가능한 위젯
class MyListWidget extends StatefulWidget {
@override
State<StatefulWidget> createState() {
return _MyListWidgetState();
}
}
// 메인 화면의 상태 관리 클래스
class _MyListWidgetState extends State<MyListWidget> {
// 각 위젯이 유니크 키를 가지도록 설정
List<Widget> widgetList = [
MyColorItemWidget(Colors.red, key: UniqueKey()),
MyColorItemWidget(Colors.blue, key: UniqueKey()),
];
// 버튼을 누를 시 동작하는 함수
onChange() {
// 위젯의 키값 출력
print(widgetList.elementAt(0).key);
// 위젯의 위치 변경
setState(() {
widgetList.insert(1, widgetList.removeAt(0));
});
}
// UI 빌드
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text('Key Test')),
body: Column(
children: [
Row(children: widgetList), // Row 안에 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);
}
}
class _MyColorItemWidgetState extends State<MyColorItemWidget> {
Color color;
_MyColorItemWidgetState(this.color);
@override
Widget build(BuildContext context) {
return Expanded(child: Container(color: color, width: 150, height: 150));
}
}
코드에서 눈여겨보아야할 점은 key이다.
- StatefulWidget의 상태 유지를 위한 key의 역할을 알아야 한다.
- UniqueKey() 함수를 사용하여 위젯에 key 지정한다.
- 상태를 재성성하는 것이 아닌 단순히 위치만 변경된 것이다.
- key를 사용하지 않는다면 상태가 초기화될 수 있다.
toggle 버튼을 누를 때 마다 위젯의 위치(색상)이 변경되고, 위젯의 키 값이 콘솔에 출력된다.
'Flutter' 카테고리의 다른 글
플러터 - 텍스트 위젯 (0) | 2025.04.02 |
---|---|
플러터 - 애셋 (0) | 2025.04.01 |
플러터 - 동적 화면 생성 (0) | 2025.03.24 |
플러터 - 정적 화면 생성 (0) | 2025.03.24 |
플러터 - 위젯 트리 구조 (0) | 2025.03.22 |