반응형
일반적인 ListView는 Drag and Drop이 안된다.
Drag and Drop을 지원하는, Flutter 내장 뷰 ReorderableListView가 있다.
기존 ListView를 ReorderableListView로 옮기는 상황을 예로 보여드리고자 합니다.
class _MyWidgetState extends State<MyWidget> {
List<String> items = ["one", "two", "three", "four", "five"];
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(title: Text('${items[index]}'));
}
);
}
}
추가된 것은 두가지다.
onReorder : 인자 구현과
ListTile 내의 key: 인자 구현이다.
class _MyWidgetState extends State<MyWidget> {
List<String> items = ["one", "two", "three", "four", "five"];
@override
Widget build(BuildContext context) {
return ReorderableListView.builder(
onReorder: (int oldIndex, int newIndex) {
setState(() {
if (oldIndex < newIndex) {
newIndex -= 1;
}
final item = items.removeAt(oldIndex);
items.insert(newIndex, item);
});
},
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(title: Text('${items[index]}'), key: Key('$index'));
}
);
}
}
이대로 구현해서 만족하지 않는 사람들이 계실 것이 분명하다.
이 상태에선, LongClick을 통한 Drag Drop만이 움직임을 제어할 수 있다.
trailing 아이콘 같은 것을 통해서, 클릭만으로도 움직이게 하는 방법이 있다.
나머진 다 동일한데, trailing만 추가되었다.
class _MyWidgetState extends State<MyWidget> {
List<String> items = ["one", "two", "three", "four", "five"];
@override
Widget build(BuildContext context) {
return ReorderableListView.builder(
onReorder: (int oldIndex, int newIndex) {
setState(() {
if (oldIndex < newIndex) {
newIndex -= 1;
}
final item = items.removeAt(oldIndex);
items.insert(newIndex, item);
});
},
itemCount: items.length,
itemBuilder: (context, index) {
return ListTile(title: Text('${items[index]}'), key: Key('$index'), trailing: ReorderableDragStartListener(
index: index, child: Icon(Icons.drag_handle)),);
}
);
}
}
반응형
'[Flutter]' 카테고리의 다른 글
[Flutter] 객체 디스크에 저장 (Feat. SharedPreferences with json) (0) | 2022.11.06 |
---|---|
[Flutter] GridView bottom overflow 대응 (0) | 2022.11.03 |
[Flutter] JSON 통신 예제 (0) | 2022.10.25 |
[Flutter] Future / async / await 예제 메모 4 (0) | 2022.09.26 |
[Flutter] 버전 코드 / 버전 관리 / 스토어 버전 관리 (0) | 2022.07.16 |