在我的Ffltter应用程序中,我使用的是AnimatedList
,有AnimatedList
个项目,屏幕上一次只能显示几个项目.
当我第一次运行它时,我可以在日志(log)中看到只构建了必要的项.但如果我刷新列表的内容,出于某种原因,AnimatedList
会重新构建每一项,这会让我的应用程序变得滞后.
以下是代码:
class _MyHomePageState extends State<MyHomePage> {
static const _durationMin = Duration(microseconds: 1);
final List<String> _items = List.generate(100, (index) => "Item at $index");
final GlobalKey<AnimatedListState> _listKey = GlobalKey();
late ScrollController _scrollController;
@override
void initState() {
super.initState();
_scrollController = ScrollController(initialScrollOffset: 0);
}
@override
void dispose() {
_scrollController.dispose();
super.dispose();
}
void _onUpdate() {
_listKey.currentState?.removeAllItems((_, __) => const SizedBox.shrink(), duration: _durationMin);
_listKey.currentState?.insertAllItems(0, _items.length, duration: _durationMin);
}
Widget _buildItemWidget(String text) {
return ListTile(
title: Text(text),
trailing: IconButton(
icon: const Icon(Icons.remove),
onPressed: () {},
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: SafeArea(
child: AnimatedList(
key: _listKey,
padding: EdgeInsets.zero,
controller: _scrollController,
initialItemCount: _items.length,
itemBuilder: (context, index, animation)
{
print("index : $index");
return _buildItemWidget(_items[index]);
},
),
),
floatingActionButton: FloatingActionButton(
onPressed: _onUpdate,
child: const Icon(Icons.refresh),
),
);
}
}
因此,当我运行这款应用时,我在日志(log)中看到了以下内容:
index : 0
...
index : 18
但如果我按下浮动操作按钮,这是我在日志(log)中看到的:
index : 0
...
index : 99
为什么我会有这样的行为?我如何修复它,以便当我按下浮动操作按钮时,它只重建必要的项?
谢谢你的帮助