gpt4 book ai didi

flutter - 更改BottomNavigationBar中的页面时,强制Flutter不会丢失数据

转载 作者:行者123 更新时间:2023-12-03 04:18:36 25 4
gpt4 key购买 nike

我的flutter应用程序有一个bottomNavigationBar小部件,它实际上可以正常工作,所以...
问题是我将页面更改为另一页面后,我从API调用中丢失了数据,然后当我回来时,我必须再次对所有内容进行re-fetch!
避免这种情况的最佳方法是什么?
编码


// ...Some code...

class _HomeState extends State<Home> {
List<wp.Post> posts = [];
int _pageNumber = 1;

Future<String> getPosts() async {
var res = await fetchPosts(_pageNumber);
setState(() {
posts = res;
});
return "Success!";
}

// Get posts when app loads;
@override
void initState() {
super.initState();
this.getPosts();
}

@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: posts == null ? 0 : posts.length,
itemBuilder: (BuildContext context, int index) {
return buildPost(context, posts, index); //Building the posts list view
},
);
}
}

最佳答案

您可以使用`AutomaticKeepAliveClientMixin”来保持页面状态。

class _HomeState extends State<Home> with AutomaticKeepAliveClientMixin { //<== add mixin
List<wp.Post> posts = [];
int _pageNumber = 1;

@override
bool get wantKeepAlive => true; //<== add this line

Future<String> getPosts() async {
var res = await fetchPosts(_pageNumber);
setState(() {
posts = res;
});
return "Success!";
}

// Get posts when app loads;
@override
void initState() {
super.initState();
this.getPosts();
}

@override
Widget build(BuildContext context) {

super.build(context); // <== add this line
return ListView.builder(
itemCount: posts == null ? 0 : posts.length,
itemBuilder: (BuildContext context, int index) {
return buildPost(context, posts, index); //Building the posts list view
},
);
}
}

关于flutter - 更改BottomNavigationBar中的页面时,强制Flutter不会丢失数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63885181/

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