gpt4 book ai didi

flutter - 防止 ListView 重绘 Flutter 中的所有项目

转载 作者:行者123 更新时间:2023-12-03 02:47:32 33 4
gpt4 key购买 nike

我使用 FutureBuilder 在我的 listView 中构建项目。
第一次调用没问题,但在第二次,甚至更多,所有项目都被重新创建,而不仅仅是新闻;这会在添加新项目时创建剪辑效果。
我检查小部件是否必须在 scrollController 中进行 API 调用。
这是我的代码:

class _Page2State extends State<Page2> {
ScrollController _scrollController = new ScrollController();
List _pokemonLightList = [];
String _nextUrl;

@override
void initState() {
_scrollController.addListener(() {
if (_scrollController.position.pixels ==
_scrollController.position.maxScrollExtent) {
setState(() {});
}
});
super.initState();
}

@override
void dispose() {
_scrollController.dispose();
super.dispose();
}

@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(title: new Text("Dynamic Demo")),
body: FutureBuilder(
future: bloc.getPokemonLightList(_nextUrl),
builder: (BuildContext context,
AsyncSnapshot<PokemonLightList> snapshot) {
if (snapshot.hasError)
return new Text('Error: ${snapshot.error}');
else {
switch (snapshot.connectionState) {
case ConnectionState.none:
case ConnectionState.waiting:
return Center(child: CircularProgressIndicator());
default:
if (snapshot.hasData) {
_nextUrl = snapshot.data.next;
_pokemonLightList.addAll(snapshot.data.results);
}
return _buildList(_pokemonLightList);
}
}
}));
}

Widget _buildList(List list) {
return ListView.separated(
key: PageStorageKey('myListView'),
shrinkWrap: true,
primary: false,
//+1 for progressbar
itemCount: list.length + 1,
separatorBuilder: (context, index) {
return Divider();
},
itemBuilder: (BuildContext context, int index) {
if (index == list.length) {
return Center(child: CircularProgressIndicator());
} else {
return Card(
color: Colors.amberAccent,
child: Padding(
padding: const EdgeInsets.all(12.0),
child: Column(
children: <Widget>[
Text(
(list[index].name),
style: TextStyle(color: Colors.black),
),
Text(
(list[index].url),
style: TextStyle(color: Colors.black),
),
],
)),
);
}
},
controller: _scrollController,
);
}
}

这是剪裁效果: https://ibb.co/BnGWsfr

谢谢你的帮助

最佳答案

原因 didUpdateWidgetFutureBuilder每次发出重建时都会调用 state。这个函数检查旧的 future 对象是否与新的不同,如果是,则重新触发 FutureBuilder .
您可以引用 https://github.com/flutter/flutter/issues/11426#issuecomment-414047398 中的详细信息
https://medium.com/saugo360/flutter-my-futurebuilder-keeps-firing-6e774830bc2

解决方案

Future _future;

@override
void initState() {
_future = bloc.getPokemonLightList();

_scrollController.addListener(() {
if (_scrollController.position.pixels ==
_scrollController.position.maxScrollExtent) {
setState(() {
bloc.getPokemonLightList(_nextUrl);
});
}
});

super.initState();
}

FutureBuilder(
future: _future,

关于flutter - 防止 ListView 重绘 Flutter 中的所有项目,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59967517/

33 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com