Flutter 拖拽排序組件 ReorderableListView

注意:無特殊說明,Flutter版本及Dart版本如下:

  • Flutter版本: 1.12.13+hotfix.5
  • Dart版本: 2.7.0

ReorderableListView是通過長按拖動某一項到另一個位置來重新排序的列表組件。

ReorderableListView需要設置childrenonReorder屬性,children是子控件,onReorder是拖動完成後的回調,用法如下:

List<String> items = List.generate(20, (int i) => '$i');
ReorderableListView(
  children: <Widget>[
    for (String item in items)
      Container(
        key: ValueKey(item),
        height: 100,
        margin: EdgeInsets.symmetric(horizontal: 50, vertical: 10),
        decoration: BoxDecoration(
            color:
                Colors.primaries[int.parse(item) % Colors.primaries.length],
            borderRadius: BorderRadius.circular(10)),
      )
  ],
  onReorder: (int oldIndex, int newIndex) {
    if (oldIndex < newIndex) {
      newIndex -= 1;
    }
    var child = items.removeAt(oldIndex);
    items.insert(newIndex, child);
    setState(() {});
  },
)

ReorderableListView的每個子控件必須設置唯一的key,ReorderableListView沒有“懶加載”模式,需要一次構建所有的子組件,所以ReorderableListView並不適合加載大量數據的列表,它適用於有限集合且需要排序的情況,比如手機系統裏面設置語言的功能,通過拖動對語言排序。

onReorder是拖動完成的回調,第一個參數是舊的數據索引,第二個參數是拖動到位置的索引,回調裏面需要對數據進行排序並通過setState刷新數據。

效果如下:

header參數顯示在列表的頂部,用法如下:

ReorderableListView(
  header: Text(
    '一枚有態度的程序員',
    style: TextStyle(color: Colors.red,fontSize: 20),
  )
  ...
)

效果如下:

reverse`參數設置爲true且ReorderableListView的滾動方向爲垂直時,滾動條直接滑動到底部,如果是水平方向則滾動條直接滑動到右邊,默認爲false,用法如下:

ReorderableListView(
  reverse: true,
  ...
)

scrollDirection`參數表示滾動到方向,默認爲垂直,設置爲水平方向如下:

ReorderableListView(
  scrollDirection: Axis.horizontal,
  ...
)

由於改爲水平滾動,所以子控件的寬度要設置,否則會出現沒有列表。

效果如下:

今天的文章對大家是否有幫助?如果有,請在文章底部留言和點贊,以表示對我的支持,你們的留言、點贊和轉發關注是我持續更新的動力!

更多相關閱讀:

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章