在Flutter PageView中切换页面时丢失小部件状态 [英] Losing widget state when switching pages in a Flutter PageView

查看:337
本文介绍了在Flutter PageView中切换页面时丢失小部件状态的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在由PageController管理的PageView中,我有一系列有状态的小部件.我正在使用pageController.jumpToPage(index)切换页面.切换页面时,所有状态似乎都在窗口小部件中丢失,就好像是从头开始重新创建时一样.我曾尝试在PageController中使用keepPage: true,但这似乎没有任何效果.这是PageView的预期行为,还是我做错了什么?任何建议表示赞赏,谢谢!

I have a series of stateful widgets in a PageView managed by a PageController. I am using pageController.jumpToPage(index) to switch pages. When switching pages all state appears to be lost in the widget, as if it was recreated from scratch. I have tried using keepPage: true in the PageController but that doesn't seem to have any effect. Is this the intended behavior of a PageView or am I doing something wrong? Any suggestions appreciated, thanks!

推荐答案

keepPage: true是默认行为;这意味着PageController会记住销毁并重新创建的页面.这不是你想要的.

keepPage: true is the default behavior; it means that the PageController will remember what page it's on if it is destroyed and recreated. This isn't what you want.

相反,将特定于页面的 PageStorageKey 传递给页面的构造函数.这有助于Flutter为您的页面提供一个独特的存储桶.然后,在要恢复到以前状态的State中,可以使用PageStorage.of(context)获取存储桶,可以将read中的值从initStatewrite中的值更改为存储区.您可以在 ExpansionTile .

Instead, pass a page-specific PageStorageKey to the constructor of the pages. This helps Flutter give a unique storage bucket to your page. Then in your State that you want to have restored to its previous condition, you can use PageStorage.of(context) to get the storage bucket, which you can read values from in initState and write values to when they change. You can see an example in ExpansionTile.

这篇关于在Flutter PageView中切换页面时丢失小部件状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆