[flutter] 플러터에서의 Swipeable 리스트 스크롤 처리 방법

Flutter 어플리케이션을 개발할 때 Swipeable 리스트를 구현하면 사용자 경험을 향상시키는 요소 중 하나입니다. 여기에는 여러 가지 방법이 있지만, 이번 글에서는 Swipeable 리스트 스크롤 처리 방법에 대해 알아보겠습니다.


Swipeable 리스트 개요

Swipeable 리스트란 항목을 좌우로 스와이프하여 추가 옵션을 보거나 수행할 수 있는 리스트를 말합니다. 예를 들어, 메시지 앱에서 특정 메시지를 스와이프하면 삭제, 보관함 이동 등의 옵션을 볼 수 있습니다.

Swipeable 리스트 스크롤 처리 방법

1. Dismissible 위젯 활용

Flutter에서는 Dismissible 위젯을 사용하여 스와이프 동작을 쉽게 구현할 수 있습니다. Dismissible 위젯은 사용자가 스와이프하여 항목을 제거할 수 있도록 해주며, onDismissed 콜백을 통해 해당 이벤트를 처리할 수 있습니다.

다음은 Dismissible 위젯을 사용한 Swipeable 리스트의 예시 코드입니다.

ListView.builder(
  itemCount: items.length,
  itemBuilder: (context, index) {
    final item = items[index];
    return Dismissible(
      key: Key(item.id),
      onDismissed: (direction) {
        setState(() {
          items.removeAt(index);
        });
        // Handle the item dismissal
      },
      background: Container(
        color: Colors.red,
        child: Icon(Icons.delete),
      ),
      child: ListTile(
        title: Text(item.title),
      ),
    );
  },
)

이 예시에서는 ListView.builder 내부에서 Dismissible 위젯을 사용하여 Swipeable 리스트를 만들고, 사용자가 리스트 아이템을 좌우로 스와이프할 때 항목을 삭제할 수 있도록 처리하고 있습니다.

2. 외부 패키지 활용

Flutter에서는 다양한 외부 패키지를 활용하여 Swipeable 리스트를 구현할 수도 있습니다. flutter_slidable 패키지는 Swipeable 리스트를 손쉽게 구현할 수 있도록 도와주는데, 다양한 커스텀 옵션을 제공합니다.

다음은 flutter_slidable 패키지를 사용한 Swipeable 리스트의 예시 코드입니다.

Slidable(
  actionPane: SlidableDrawerActionPane(),
  actionExtentRatio: 0.25,
  child: ListTile(
    title: Text('Title'),
  ),
  actions: <Widget>[
    IconSlideAction(
      caption: 'Archive',
      color: Colors.blue,
      icon: Icons.archive,
      onTap: () {
        // Handle archive action
      },
    ),
  ],
  secondaryActions: <Widget>[
    IconSlideAction(
      caption: 'Delete',
      color: Colors.red,
      icon: Icons.delete,
      onTap: () {
        // Handle delete action
      },
    ),
  ],
)

위의 코드는 flutter_slidable 패키지를 사용하여 Swipeable 리스트를 구현한 예시입니다. Slidable 위젯을 사용하여 좌우로 스와이프할 때 나타나는 옵션을 설정하고 있습니다.


Swipeable 리스트를 스크롤하기 위한 다양한 방법이 존재하며, 위에서 설명한 방법 외에도 다른 방법들도 존재합니다. 프로젝트의 요구에 맞게 적절한 방법을 선택하여 Swipeable 리스트를 구현해보시기 바랍니다.