아래 코드를 참고하다가 문득 궁금해졌다.
왜 리스트 타일 안에 key가 들어가 있을까?
결론
UI적으로 아무런 의미는 없지만 프로그램이 돌아가는 동안에 각 리스트 타일에 key값을 할당한다.
그러면 후에 특정 값만 업데이트 하고 싶을 때 쉽게 접근이 가능해진다.
복잡한 구조의 리스트를 사용할 때 쓰면 좋다.
ListTile(
key: UniqueKey(),
title: Center(child: Text("Add Ingredient")),
onTap: () {
addOnTap();
},
),
ListTile(
key: UniqueKey(),
title: Row(
children: <Widget>[
Expanded(
flex: 4,
child: Container(
margin: EdgeInsets.all(2),
// height: 60,
color: Colors.grey[200],
child: Center(
child: ListSectionHeader(
"Recipe Directions",
),
),
),
),
],
),
),
ListTile(
key: UniqueKey(),
title: Row(
children: <Widget>[
Expanded(
child: CustomEditableText(
recipe: widget.recipe,
),
),
Using a key in a ListTile is optional, but it can be helpful in certain cases, such as when you need to uniquely identify a specific widget for purposes such as testing, or if you need to track which items in a list have changed and need to be updated.In the example code you provided, each ListTile has a UniqueKey() assigned to it, which ensures that each ListTile instance has a unique identity. This can be helpful if you need to track changes to the list over time, or if you want to ensure that the same item is not added to the list more than once.
Using unique keys can also improve performance when the list is being updated or animated, as it allows Flutter to quickly identify which items have changed and need to be updated, rather than rebuilding the entire list from scratch.
Overall, while using keys in ListTile is optional, it can be a helpful practice in certain cases, especially when dealing with complex UIs or dynamic lists.
List<Widget> myItems = [
ListTile(
key: UniqueKey(),
title: Text("Item 1"),
),
ListTile(
key: UniqueKey(),
title: Text("Item 2"),
),
ListTile(
key: UniqueKey(),
title: Text("Item 3"),
),
];
ListView(
children: myItems,
);
In this example, we have a list of ListTile widgets stored in the myItems list. Each ListTile has a UniqueKey() assigned to it. We then display the list of ListTile widgets in a ListView.
By assigning a unique key to each ListTile, we can easily identify which items in the list have changed and need to be updated. For example, if we add a new item to the list, we can create a new ListTile with a new UniqueKey() and add it to the myItems list. When we update the ListView, Flutter will know which items have changed and will only update those items, rather than rebuilding the entire list from scratch.
'Flutter-플러터 > 플러터 공부' 카테고리의 다른 글
Get X - lazyPut (0) | 2023.03.22 |
---|---|
플러터로 디버깅 하는 방법 (0) | 2023.03.17 |
Flutter : list<모델> aa =[]; 의 위치와 위젯의 생애주기 (0) | 2023.02.15 |
Flutter : Expanded와 SingleChildScrollView 의 차이점 (0) | 2023.02.14 |
Flutter : DateTime (0) | 2023.02.13 |