dev/flutter
[Flutter] AnimatedList
donguran
2024. 3. 6. 17:37
728x90
반응형
AnimatedList에 필요한 것은 바로 GlobalKey<AnimatedListState> 객체이다.
final GlobalKey<AnimatedListState> _globalListKey = GlobalKey<AnimatedListState>();
_globalListKey라는 객체를 만들어주고,
다음으로 AnimatedListState 를 호출한다.
AnimatedListState? get _animatedList => _globalListKey.currentState;
준비 끝.
AnimatedList위젯에는 3가지 파라메터가 충족되면 된다.
- key
- initialItemCount
- itemBuilder
key에는 앞서 만들어주면 GlobalKey<AnimatedListState>객체 인자가 되면 되고,
initialItemCount는 데이터 개수를 기입한다.
itemBuilder는 리스트내에 표시될 아이템이다.
child: AnimatedList(
key: globalListKey,
initialItemCount: datas.length,
itemBuilder: (context, index, animation) => SizeTransition(
sizeFactor: animation,
child: Card(child: ListTile(child: Text("data$index"))),
)
),
데이터 추가하는 방법
.insertItem() 사용
직접 만든 데이터리스트에 add해주거나, 또는 insert하고,
앞서 만든 AnimatedListState 를 사용하여 데이터를 기입하면 애니메이션 동작이 되도록 한다.
void add(var data) {
datas.add(data);
_animatedList!.insertItem(datas.lastIndexOf(data));
}
데이터 제거하는 방법
.removeItem() 사용
데이터를 제거할 땐 앞서 AnimatedList의 itemBuilder에서 사용했던 위젯과 동일하거나 또는 뼈대가 동일한 위젯을 사용해야한다. 이것은 직접 구현해보아야 이해될 것이다.
(전체 데이터를 제거할 경우 removeAllItems를 사용해서 제거하는 것을 권장한다 : UI가 따라가질 못한다.)
void remove(var data) {
int index = datas.lastIndexOf(data);
_animatedList!.removeItem(index, (context, (context, animation) =>
SizedTransition(
sizeFactor: animation,
child: Card(child: ListTile()),
)
}
728x90
반응형