【Flutter】ReorderableListViewを使って順序を入れ替えできるリストを作る

ネコニウム研究所

PCを利用したモノづくりに関連する情報や超個人的なナレッジを掲載するブログ

【Flutter】ReorderableListViewを使って順序を入れ替えできるリストを作る

2024-6-6 | ,

FlutterでReorderableListViewを使って順序を入れ替えできるリストを作りたい!

概要

今回の記事では、FlutterでReorderableListViewを使って順序を入れ替えできるリストを作る手順を掲載する。

ReorderableListViewを使うとドラッグでリストの要素の順序を入れ替えることがメチャクチャ簡単にできる。(少なくとも自分で実装するには)

仕様書

環境

  • Android Studio Giraffe | 2023.2.1 Patch 2
  • Flutter 3.19.6

手順書

appbarのタイトルの左のアイコンをタップするとdrawerが表示される例。

import 'package:flutter/material.dart';

void main() {
  runApp(
    MaterialApp(
      home: Scaffold(
        body: const ReorderableListViewSample1()
      )
    )
  );
}

class ReorderableListViewSample1 extends StatefulWidget {
  const ReorderableListViewSample1({super.key});

  @override
  ReorderableListViewSample1State createState() => ReorderableListViewSample1State();
}

class ReorderableListViewSample1State extends State<ReorderableListViewSample1> {
  List<String> list = ["Apple", "Bear", "Cat", "Decadence", "Exp", "File", "Godspeed", "Hex", "Iron" , "Joker", "Keep", "Leek", "Opaque", "Picnic", "Que", "Resonance", "Salt", "Tooth", "Under" ,"Vanguard", "Whisky", "Xray", "Zine"];

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Center(
        child: SizedBox(
          width: double.infinity,
          child: ReorderableListView(
            onReorder: (int oldIndex, int newIndex) {
              setState(() {
                if (newIndex > oldIndex) {
                  newIndex -= 1;
                }
                final item = list.removeAt(oldIndex);
                list.insert(newIndex, item);
              });
            },
            children: List.generate(list.length, (index) {
              return Card(
                key: ValueKey(list[index]),
                child: ListTile(
                  title: Text(list[index])
                ),
              );
            }),
          ),
        ),
      ),
    );
  }
}

StatefulWidgetなどを使わないとUIへの反映のタイミングが順序入れ替えの後に行われなかったりするので注意。

onReorderにドラッグが行われた時の処理を書く。単純なリストであれば例のとおりで良い。自分で作ったクラスのListを使う場合や独自の処理を行いたい場合はここに書く。

デスクトップアプリでは要素の右側にハンドルが表示され、ハンドルをドラッグすることで要素を移動できる。
モバイルアプリの場合はロングタップすることで要素を移動できる。

まとめ(感想文)

自分でドラッグアンドドロップの処理を書かなくて済むのはめちゃ楽!

たーだ、デスクトップアプリでもロングタップで要素を移動したい場合は、自分で実装しないとだめっぽい。ので諦めた。

参考文献・引用

下記の記事を参考にさせていただきました。ありがとうございました。