天天看點

Flutter 拖拽排序元件 ReorderableListView

Flutter 拖拽排序元件 ReorderableListView
注意:無特殊說明,Flutter版本及Dart版本如下:
  • Flutter版本: 1.12.13+hotfix.5
  • Dart版本: 2.7.0

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

ReorderableListView需要設定

children

onReorder

屬性,

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

重新整理資料。

效果如下:

Flutter 拖拽排序元件 ReorderableListView

header

參數顯示在清單的頂部,用法如下:

ReorderableListView(
  header: Text(
    '一枚有态度的程式員',
    style: TextStyle(color: Colors.red,fontSize: 20),
  )
  ...
)           
Flutter 拖拽排序元件 ReorderableListView

reverse`參數設定為true且ReorderableListView的滾動方向為垂直時,滾動條直接滑動到底部,如果是水準方向則滾動條直接滑動到右邊,預設為false,用法如下:

ReorderableListView(
  reverse: true,
  ...
)           

scrollDirection`參數表示滾動到方向,預設為垂直,設定為水準方向如下:

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

由于改為水準滾動,是以子控件的寬度要設定,否則會出現沒有清單。

Flutter 拖拽排序元件 ReorderableListView

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

更多相關閱讀:

繼續閱讀