我的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/