我目前有一个SliverList动态加载的项目。问题在于,一旦加载了这些项目,SliverList更新就不会设置动画效果,这使得加载和加载之间的过渡非常困难。
我看到AnimatedList存在,但它不是条子,因此无法将其直接放在CustomScrollView。
您现在可能知道这一点,但不妨在这里提及它以帮助人们。
您可以使用SliverAnimatedList。它达到了所需的结果。
SliverAnimatedList 构造:
itemBuilder定义新项目的构建方式。构建器通常应返回一个Transition小部件或任何将使用该animation参数的小部件。
SliverAnimatedList(
key: someKey,
initialItemCount: itemCount,
itemBuilder: (context, index, animation) => SizeTransition(
sizeFactor: animation,
child: SomeWidget()
)
)
Run Code Online (Sandbox Code Playgroud)
动态添加/删除
您可以通过使用insertItem和removeItem的方法来做到这一点SliverAnimatedListState。您可以通过以下任一方式访问状态:
Key并SliverAnimatedList使用key.currentStateSliverAnimatedList.of(context)静态方法。如果您需要从列表外部进行更改,则始终需要使用该密钥。
这是一个完整的例子来澄清事情。通过点击 来添加项目FloatingActionButton,通过点击项目本身来删除项目。我使用了key和两种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,
)));
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
533 次 |
| 最近记录: |