我试图使用ReorderableListView与Dissmissable功能。数据以列表的形式从API中获取。可撤销特性在下面的代码中不起作用。
注意:当我使用Listview时,下面的代码工作正常。构建器。
ReorderableListView.builder(
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
onReorder: (int oldIndex, int newIndex) {
if (oldIndex != newIndex) {
//reorder action
},
itemCount: list.length,
scrollDirection: Axis.horizontal,
itemBuilder: (context, index) {
return Dismissible(
direction: DismissDirection.up,
onDismissed: (direction) {},
key: UniqueKey(),
child: ReorderableDragStartListener(
key: UniqueKey(),
index: index,
child: SizedOverflowBox(
alignment: Alignment.bottomLeft,
size: const Size(50, 10),
child: Image(
image: AssetImage("assets/${list[index]}.png"),
),
),
),
);
},
),
###这里的错误是,最初你不能滑动来解散,因为ReorderableDragStartListener不允许dis来解散它。
一个最好的解决方案是有一个机制来在重新排序和解散之间切换。
下面是我想到的一个解决办法:
import 'package:flutter/material.dart';
const Color darkBlue = Color.fromARGB(255, 18, 32, 47);
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: MyWidget(),
);
}
}
class MyWidget extends StatefulWidget {
@override
State<MyWidget> createState() => _MyWidgetState();
}
class _MyWidgetState extends State<MyWidget> {
List<String> list = ["1", "2", "3"];
bool reorder;
@override
void initState() {
super.initState();
reorder = false;
}
@override
Widget build(BuildContext context) {
return Scaffold(
floatingActionButton: FloatingActionButton.extended(
label: reorder ? const Text("Done") : const Text("Reorder"),
onPressed: () {
setState(() {
reorder = !reorder;
});
}),
body: reorder
? ReorderableListView.builder(
key: UniqueKey(),
shrinkWrap: true,
physics: const NeverScrollableScrollPhysics(),
onReorder: (int oldIndex, int newIndex) {
if (newIndex >= list.length) return;
print(oldIndex);
print(newIndex);
setState(() {
var tmp = list[oldIndex];
list[oldIndex] = list[newIndex];
list[newIndex] = tmp;
print(list);
});
},
itemCount: list.length,
itemBuilder: (context, index) {
return ReorderableDragStartListener(
index: index,
key: ValueKey(index),
child: ListTile(title: Text("${list[index]}")),
);
},
)
: ListView.builder(
itemCount: list.length,
itemBuilder: (c, i) {
return Dismissible(
key: UniqueKey(),
background: Container(color: Colors.red),
onDismissed: (direction) {
setState(() {
list.removeAt(i);
});
},
child: ListTile(title: Text("${list[i]}")),
);
}),
);
}
}
这里我们只是简单地使用reorder变量来切换模式