Flutter AnimatedListView: 并发删除和新增项
可以使用Future.delayed和setState方法来实现在AnimatedListView中并发删除和新增项。下面是一个示例代码:
class MyAnimatedListView extends StatefulWidget {
@override
_MyAnimatedListViewState createState() => _MyAnimatedListViewState();
}
class _MyAnimatedListViewState extends State<MyAnimatedListView> {
List<String> _items = ['Item 1', 'Item 2', 'Item 3', 'Item 4'];
bool _isDeleting = false;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('AnimatedListView'),
),
body: AnimatedList(
key: Key(_items.length.toString()),
initialItemCount: _items.length,
itemBuilder: (BuildContext context, int index, Animation<double> animation) {
return _buildItem(_items[index], animation);
},
),
floatingActionButton: FloatingActionButton(
onPressed: _isDeleting ? null : _addItem,
child: Icon(Icons.add),
),
);
}
Widget _buildItem(String item, Animation<double> animation) {
return SizeTransition(
sizeFactor: animation,
child: ListTile(
title: Text(item),
trailing: IconButton(
icon: Icon(Icons.delete),
onPressed: _isDeleting ? null : () => _removeItem(item),
),
),
);
}
void _addItem() {
int newIndex = _items.length;
_items.insert(newIndex, 'Item ${newIndex + 1}');
setState(() {
_isDeleting = false;
});
}
void _removeItem(String item) {
int index = _items.indexOf(item);
_items.removeAt(index);
setState(() {
_isDeleting = true;
});
Future.delayed(Duration(milliseconds: 500), () {
setState(() {
_isDeleting = false;
});
});
}
}
在这个示例代码中,我们首先创建了一个包含四个项的 _items 列表,并在 AnimatedList 中使用它。
当用户点击浮动操作按钮时,我们会在 _items 列表中添加一个新项。当用户点击列表项的删除按钮时,我们会在 _items 列表中删除该项。
为了实现并发删除和新增项,我们使用了 _isDeleting 状态变量来控制是否可以添加或删除项。当用户点击删除按钮时,我们首先将 _isDeleting 设置为 true,这样用户就不能添加或删除项。然后,我们使用 Future.delayed 方法来延迟 500 毫秒,等待动画完成。在延迟结束后,我们会将 _isDeleting 设置为 false,这样用户就可以继续添加或删除项了。
原文地址: https://www.cveoy.top/t/topic/lH0c 著作权归作者所有。请勿转载和采集!