作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我使用 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,
);
}
}
最佳答案
原因 didUpdateWidget
的FutureBuilder
每次发出重建时都会调用 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/
我是一名优秀的程序员,十分优秀!