gpt4 book ai didi

dart - 即使其潜在的 future 没有改变,如何防止 FutureBuilder 的重建

转载 作者:行者123 更新时间:2023-12-03 03:01:49 24 4
gpt4 key购买 nike

在 Flutter 中,我得到了不需要的重建。在我的情况下,我使用 FutureBuilder 通过获取 db 结果来显示列表,这是一个 future 并且依赖于查询参数。我试图让 FutureBuilder 的 future 在查询参数不变的情况下不会改变,但是每次仍然调用 FutureBuilder 的构建器块。我怎样才能让 FutureBuilder 不会在其 future 不变的情况下重建自己。

下面是我的代码,每次 MusicList2 的父小部件构建时, MusicList2 都会重建,它的 FutureBuilder 会重建。

class MusicList2 extends StatefulWidget {
final MusicRowActionCallback onTapItem;
final MusicRowActionCallback onDoubleTap;
final MusicRowActionCallback onLongPressed;
final String facetName;
final String facetValue;
const MusicList2(
{Key key,
this.onTapItem,
this.onDoubleTap,
this.onLongPressed,
this.facetName,
this.facetValue}) : super(key: key);
@override
State<StatefulWidget> createState() {

return _MusicList2State();
}


}

class _MusicList2State extends State<MusicList2> {
Future<List<Music>> loadMusicByFacet;
@override
Widget build(BuildContext context) {

return FutureBuilder<List<Music>>(
future:
loadMusicByFacet,
builder: (context, snapshot) {
if (snapshot.data == null)
return Center(child: CircularProgressIndicator(),);
return ListView.builder(
shrinkWrap: true,
key: const ValueKey<String>('music-list'),
itemCount: snapshot.data.length,
itemBuilder: (BuildContext context, int index) {
final random = Random();
var i = random.nextInt(5);
return MusicRow(
avatarBgColor: colors[i],
music: snapshot.data[index],
onTap: widget.onTapItem,
onDoubleTap: widget.onDoubleTap,
onLongPressed: widget.onLongPressed,
);
},
);
},
);
}

@override
void initState() {
super.initState();
loadMusicByFacet = MusicsDatabaseRepository.get.getMusicsByFacet(widget.facetName, widget.facetValue);
}
@override
void didUpdateWidget(MusicList2 oldWidget) {
super.didUpdateWidget(oldWidget);
if (oldWidget.facetValue != widget.facetValue || oldWidget.facetName != widget.facetName) {
loadMusicByFacet = MusicsDatabaseRepository.get.getMusicsByFacet(widget.facetName, widget.facetValue);
}
}
}

最佳答案

对于遇到此错误的其他人,我使用 AbdulRahmanAlHamali 解决了它GitHub 上的解决方案。这是他的回答:

Hello, I believe the problem here is that didUpdateWidget of the FutureBuilder state is being called every time a rebuild is issued. This function checks if the old future object is different from the new one, and if so, refires the FutureBuilder.

To get past this, we can call the Future somewhere other than in the build function. For example, in the initState, and save it in a member variable, and pass this variable to the FutureBuilder.

So instead of having:

FutureBuilder(
future: someFunction(),
....

We should have:

initState() {
super.initState();
_future = SomeFunction();
}

and then

FutureBuilder(
future: _future,
....


找原帖 here .

关于dart - 即使其潜在的 future 没有改变,如何防止 FutureBuilder 的重建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55673266/

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