如何在 Flutter 中使用 BottomNavigationBar 维护 Webview 状态
How to maintain Webview state with BottomNavigationBar in Flutter
我正在创建一个使用 BottomNavigationBar 在页面之间切换的 Flutter 应用程序。在其中一个页面中,我有一个 Webview(我正在使用由 Flutter 开发团队开发的 plugin),当我导航到另一个选项卡然后返回时,我无法保持 webview 的状态.也不知道有没有办法。
我试过使用 PageStorageBucket 和 AutomaticKeepAliveClientMixin,但无济于事。我注意到在使用 PageStorageBucket 时,简单 ListView 的状态保留在选项卡之间,但它似乎不适用于 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 选项卡时,我希望 web 处于相同状态,我不希望它重新加载。
您可以为此使用 IndexedStack。它永远不会卸载 children。但是,它会一次加载它们[产生一点延迟]
body:IndexedStack(
index: _selectedIndex ,
children: <Widget>[
FirstPage(),
Webview(),
//etc...
]
),
好吧,经过一番挖掘,我设法找到了解决方案。
我没有使用 BottomNavigationBar,而是使用了 TabBar(在 bottomNavigationBar Scaffold 字段中)。
将此与 AutomaticKeepAliveClientMixin 结合使用,选项卡不会卸载,状态会在选项卡更改时保持不变。
我正在创建一个使用 BottomNavigationBar 在页面之间切换的 Flutter 应用程序。在其中一个页面中,我有一个 Webview(我正在使用由 Flutter 开发团队开发的 plugin),当我导航到另一个选项卡然后返回时,我无法保持 webview 的状态.也不知道有没有办法。
我试过使用 PageStorageBucket 和 AutomaticKeepAliveClientMixin,但无济于事。我注意到在使用 PageStorageBucket 时,简单 ListView 的状态保留在选项卡之间,但它似乎不适用于 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 选项卡时,我希望 web 处于相同状态,我不希望它重新加载。
您可以为此使用 IndexedStack。它永远不会卸载 children。但是,它会一次加载它们[产生一点延迟]
body:IndexedStack(
index: _selectedIndex ,
children: <Widget>[
FirstPage(),
Webview(),
//etc...
]
),
好吧,经过一番挖掘,我设法找到了解决方案。
我没有使用 BottomNavigationBar,而是使用了 TabBar(在 bottomNavigationBar Scaffold 字段中)。
将此与 AutomaticKeepAliveClientMixin 结合使用,选项卡不会卸载,状态会在选项卡更改时保持不变。