Flutter アニメーション付きのリストを簡単に実装できるパッケージ「animated_reorderable」

今回は「animated_reorderable」というパッケージを紹介します。

「animated_reorderable」は、ListViewやGridViewをアニメーション付きで並べ替え可能にするためのパッケージです。このパッケージを使用うことで、アイテムの追加・削除時にスムーズなアニメーションを追加でき、ドラッグ&ドロップによる並べ替え操作を簡単に実装できます。

特徴

アニメーション付きのアイテム追加・削除: リストやグリッド内のアイテムを追加・削除する際に、スムーズなアニメーションをつけることができます。

ドラッグ&ドロップによる並べ替え: ListViewやGridView内のアイテムをドラッグ&ドロップで並べ替えができます。

スワイプによる削除: アイテムをスワイプして削除する機能をサポートしています。

特定アイテムの並べ替え禁止: 特定のアイテムを並べ替え不可に設定することができます。

ドラッグやスワイプイベントのコールバック: アイテムのドラッグやスワイプイベントを追跡するためのコールバックを提供します。

基本的な使用例

animated_reorderableパッケージを使い、アニメーション付きの並べ替え可能なリストを作成する例です。

import 'package:flutter/material.dart';
import 'package:animated_reorderable/animated_reorderable.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Animated Reorderable List Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: const ReorderableListPage(),
    );
  }
}

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

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

class _ReorderableListPageState extends State<ReorderableListPage> {
  final List<String> _items = List.generate(10, (index) => 'Item ${index + 1}');

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Animated Reorderable List'),
      ),
      body: AnimatedReorderable.list(
        items: _items,
        itemBuilder: (context, item, index, animation) {
          return SizeTransition(
            sizeFactor: animation,
            child: ListTile(
              key: ValueKey(item),
              title: Text(item),
              trailing: const Icon(Icons.drag_handle),
            ),
          );
        },
        onReorder: (oldIndex, newIndex) {
          setState(() {
            if (newIndex > oldIndex) {
              newIndex -= 1;
            }
            final String item = _items.removeAt(oldIndex);
            _items.insert(newIndex, item);
          });
        },
        onSwipeToDismiss: (index) {
          setState(() {
            _items.removeAt(index);
          });
        },
      ),
    );
  }
}

ポイント解説:

1.AnimatedReorderable.list: このウィジェットは、アニメーション付きで並べ替え可能なリストを作成します。

2.itemBuilder: リスト内の各アイテムのウィジェットを構築します。animationパラメータを使用して、アイテムの挿入・削除時のアニメーションを定義できます。

3.onReorder: アイテムの並べ替えが発生した際に呼び出されるコールバック関数です。ここで、リスト内のアイテムの順序を更新します。

4.onSwipeToDismiss: アイテムがスワイプによって削除された際に呼び出されるコールバック関数です。

まとめ

animated_reorderableを使用することで、アニメーション付きの並べ替え可能なリストやグリッドを簡単に実装できます。ユーザーにとって直感的でスムーズな操作体験を提供するために、ぜひ使ってみてください!

タイトルとURLをコピーしました