[Flutter]リストビュー(listview)を並び替える方法

Flutter

どうも、ちょげ(@chogetarou)です。

リストビューを並び替える方法を紹介します。

スポンサーリンク

方法

インターフェース, インターネット, プログラム, ブラウザ, Www

ソート

リストビューをソートで並び替えるには、sortメソッドを使います。

以下は、例です。

  var _list = <int>[9, 2, 4, 1, 3, 7, 5, 10, 6, 8];

  @override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: Padding(
          padding: const EdgeInsets.all(8.0),
          child: ListView.builder(
            itemCount: _list.length,
            itemBuilder: (context, index) {
              return Text('${_list[index]}');
            },
            itemExtent: 50,
          ),
        ),
        floatingActionButton: FloatingActionButton(onPressed: () {
          setState(() {
            _list.sort((a, b) => a.compareTo(b));
          });
        }),
      ),
    );
  }

移動

リストビューを移動して、並び替えるには、ReorderableListViewを使います。

ReorderableListViewは、引数「children」に表示する要素、引数「reOrder」に並び替える処理を追加することで使えます。

ReorderableListView(
  children: [
    /*Item*/
  ],
  onReorder: (int oldIndex, int newIndex) {
    setState(() {
      if (oldIndex < newIndex) {
        newIndex -= 1;
      }
      final int item = _items.removeAt(oldIndex);
      _items.insert(newIndex, item);
    });
  },
)

まとめ

リストビューを並び替えるには、ソートで並び替えるには「sortメソッド」、移動で並び替えるには「ReorderableListView」を使います。

コメント

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