问题描述
我正在创建一个Flutter应用程序,该应用程序使用BottomNavigationBar在页面之间进行切换。在其中一页中,我有一个Webview(我使用的是Flutter开发的团队),当我导航到另一个标签然后返回时,我无法保持Web视图的状态。我也不知道是否有办法。
I'm creating a Flutter application that uses a BottomNavigationBar to change between pages. In one of the pages, I have a Webview (I'm using the plugin developed by the Flutter dev team) and I can't get to keep the state of the webview when I navigate to another tab then come back. I don't know if there is a way either.
我尝试使用PageStorageBucket以及AutomaticKeepAliveClientMixin都没有用。我注意到,使用PageStorageBucket时,简单的ListView的状态会保留在选项卡之间,但是似乎不适用于Webview。
I've tried using a PageStorageBucket and also AutomaticKeepAliveClientMixin, to no avail. I've noticed that the state of a simple ListView is kept between tabs when using PageStorageBucket, but it doesn't seem to work with a Webview.
可重现的示例:
class _MyHomePageState extends State<MyHomePage> {
List<Widget> _pages;
int _selectedIndex = 0;
@override
void initState() {
super.initState();
_pages = [
Center(
child: Text('HOME'),
),
WebView(
initialUrl: 'https://flutter.io',
javascriptMode: JavascriptMode.unrestricted,
)
];
}
@override
Widget build(BuildContext context) {
return Scaffold(
bottomNavigationBar: BottomNavigationBar(
items: [
BottomNavigationBarItem(icon: Icon(Icons.home), title: Text('Home')),
BottomNavigationBarItem(icon: Icon(Icons.web), title: Text('Web')),
],
currentIndex: _selectedIndex,
onTap: (index) {
setState(() {
_selectedIndex = index;
});
},
),
body: _pages[_selectedIndex],
);
}
当我返回时,我希望网络处于相同状态到Webview选项卡,我不希望它重新加载。
I'd want the web to be in the same state when I go back to the Webview tab, I don't want it to reload.
推荐答案
您可以为此使用IndexedStack。它将永远不会卸下孩子们。但是,它会一次全部加载它们[产生一些滞后]
You could use an IndexedStack for this. it will never unload the children. However , it will load them at all once [producing a little lag]
body:IndexedStack(
index: _selectedIndex ,
children: <Widget>[
FirstPage(),
Webview(),
//etc...
]
),
这篇关于如何在Flutter中使用BottomNavigationBar维护Webview状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!