如果我有一个可以添加、删除和交换的列表(例如 ListTiles),那么动画这些更改的最佳方法是什么?如果这有所不同,我将使用可重新排序的列表。现在我的列表没有动画,我只是在数据更改时调用 setState。
我认为你需要 AnimatedList...我写了一个例子。
您只能在想要插入列表或从列表中删除时设置 Duration,这是通过创建 AnimatedListState 的 GlobalKey 来实现的...
我写了一个示例代码用于插入
class Pool extends StatelessWidget {
final keys = GlobalKey<AnimatedListState>();
var list = List.generate(3, (i) => "Hello $i");
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: AnimatedList(
key: keys,
initialItemCount: list.length,
itemBuilder: (context, index, animation) {
return SlideTransition(
position: animation.drive(
Tween<Offset>(begin: Offset(1, 0), end: Offset(0, 0))
.chain(CurveTween(curve: Curves.ease))),
child: ListTile(
title: Text(list[index]),
),
);
},
),
),
floatingActionButton: FloatingActionButton(
onPressed: () {
list.insert(0, "NothingYay");
keys.currentState.insertItem(0, duration: Duration(seconds: 2));
},
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
我希望这可以帮助你。
我假设您正在尝试在列表中实现滑动功能。有一个手势叫 Dissmissable
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
// MyApp is a StatefulWidget. This allows us to update the state of the
// Widget whenever an item is removed.
class MyApp extends StatefulWidget {
MyApp({Key key}) : super(key: key);
@override
MyAppState createState() {
return MyAppState();
}
}
class MyAppState extends State<MyApp> {
final items = List<String>.generate(3, (i) => "Item ${i + 1}");
@override
Widget build(BuildContext context) {
final title = 'Dismissing Items';
return MaterialApp(
title: title,
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: Scaffold(
appBar: AppBar(
title: Text(title),
),
body: ListView.builder(
itemCount: items.length,
itemBuilder: (context, index) {
final item = items[index];
return Dismissible(
// Each Dismissible must contain a Key. Keys allow Flutter to
// uniquely identify Widgets.
key: Key(item),
// We also need to provide a function that tells our app
// what to do after an item has been swiped away.
onDismissed: (direction) {
// Remove the item from our data source.
setState(() {
items.removeAt(index);
});
// Then show a snackbar!
Scaffold.of(context)
.showSnackBar(SnackBar(content: Text("$item dismissed")));
},
// Show a red background as the item is swiped away
background: Container(color: Colors.red),
child: ListTile(title: Text('$item')),
);
},
),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3252 次 |
| 最近记录: |