【Flutter 问题系列第 79 篇】在 Flutter 中使用 ReorderableListView 实现拖拽排序列表组件的功能
warning:
这篇文章距离上次修改已过280天,其中的内容可能已经有所变动。
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
final title = 'Draggable List';
return MaterialApp(
title: title,
home: Scaffold(
appBar: AppBar(
title: Text(title),
),
body: const MyList(),
),
);
}
}
class MyList extends StatefulWidget {
const MyList({Key? key}) : super(key: key);
@override
_MyListState createState() => _MyListState();
}
class _MyListState extends State<MyList> {
final items = <String>[
'Item 1',
'Item 2',
'Item 3',
// ...
];
@override
Widget build(BuildContext context) {
return ReorderableListView(
children: <Widget>[
for (var item in items)
Card(
key: ValueKey(item),
child: ListTile(title: Text(item)),
),
],
onReorder: (int oldIndex, int newIndex) {
setState(() {
if (newIndex > oldIndex) {
newIndex -= 1;
}
final item = items.removeAt(oldIndex);
items.insert(newIndex, item);
});
},
);
}
}
这段代码实现了一个简单的拖拽排序列表,用户可以通过拖动列表中的卡片来重新排列它们。代码中使用了ReorderableListView
控件,并通过onReorder
回调函数处理拖拽排序的逻辑。在onReorder
函数中,我们更新了items
列表的状态,并在UI上反映出这些更改。
评论已关闭