您现在可能知道这一点,但不妨在这里提及它以帮助人们。
您可以使用银条动画列表 https://api.flutter.dev/flutter/widgets/SliverAnimatedList-class.html。它达到了所需的结果。
SliverAnimatedList 构造:
itemBuilder
定义新项目的构建方式。构建者通常应该返回一个Transition
小部件,或任何将使用animation
范围。
SliverAnimatedList(
key: someKey,
initialItemCount: itemCount,
itemBuilder: (context, index, animation) => SizeTransition(
sizeFactor: animation,
child: SomeWidget()
)
)
动态添加/删除
你可以通过使用来做到这一点insertItem
and removeItem
的方法SliverAnimatedListState
。您可以通过以下任一方式访问状态:
- 提供一个
Key
to the SliverAnimatedList
并使用key.currentState
- using
SliverAnimatedList.of(context)
静态方法。
如果您需要从列表外部进行更改,则始终需要使用该密钥。
这是一个完整的例子来澄清事情。通过点击添加项目FloatingActionButton
并通过点击项目本身来删除。我同时使用了key
and of(context)
访问方式SliverAnimatedListState
.
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
class SliverAnimatedListTest extends StatefulWidget {
@override
_SliverAnimatedListTestState createState() => _SliverAnimatedListTestState();
}
class _SliverAnimatedListTestState extends State<SliverAnimatedListTest> {
int itemCount = 2;
// The key to be used when accessing SliverAnimatedListState
final GlobalKey<SliverAnimatedListState> _listKey =
GlobalKey<SliverAnimatedListState>();
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(title: Text("Sliver Animated List Test")),
// fab will handle inserting a new item at the last index of the list.
floatingActionButton: FloatingActionButton(
child: Icon(Icons.add),
onPressed: () {
_listKey.currentState.insertItem(itemCount);
itemCount++;
},
),
body: CustomScrollView(
slivers: <Widget>[
SliverAnimatedList(
key: _listKey,
initialItemCount: itemCount,
// Return a widget that is wrapped with a transition
itemBuilder: (context, index, animation) =>
SizeTransition(
sizeFactor: animation,
child: SomeWidget(
index: index,
// Handle removing an item using of(context) static method.
// Returned widget should also utilize the [animation] param
onPressed: () {
SliverAnimatedList.of(context).removeItem(
index,
(context, animation) => SizeTransition(
sizeFactor: animation,
child: SomeWidget(
index: index,
)));
itemCount--;
}),
))
],
),
);
}
}
class SomeWidget extends StatelessWidget {
final int index;
final Function() onPressed;
const SomeWidget({Key key, this.index, this.onPressed}) : super(key: key);
@override
Widget build(BuildContext context) {
return Padding(
padding: const EdgeInsets.all(20.0),
child: Center(
child: FlatButton(
child: Text("item $index"),
onPressed: onPressed,
)));
}
}