Flutter中点击BottomNavigationBarItem后WebView无法切换URL的问题
Flutter WebView 底部导航切换页面不生效的解决方案
你当前的代码里,WebView的initialUrl仅在widget首次初始化时生效,后续setState更新_selectedIndex时,WebView不会自动重新加载新的URL——因为框架会复用已存在的WebView实例,不会重新执行初始化逻辑。
解决方案
通过WebViewController主动控制页面加载,同时处理导航项点击时的刷新逻辑,具体修改如下:
- 声明
WebViewController?变量保存控制器实例 - 在WebView的
onWebViewCreated回调中初始化控制器 - 修改
_onItemTapped方法,根据索引加载对应URL,点击当前项时触发页面刷新
修改后的完整代码
import 'package:flutter/material.dart'; import 'package:webview_flutter/webview_flutter.dart'; void main() { runApp(const MyApp()); } class MyApp extends StatefulWidget { const MyApp({Key? key}) : super(key: key); @override _MyAppState createState() => _MyAppState(); } class _MyAppState extends State<MyApp> { int _selectedIndex = 0; final List<String> _urls = [ "https://minecraft.xandersalarie.com/", "https://minecraft.xandersalarie.com/status", ]; WebViewController? _webViewController; // 新增控制器变量 void _onItemTapped(int index) { setState(() { _selectedIndex = index; }); // 加载对应URL,点击当前项时刷新页面 if (_webViewController != null) { _webViewController!.loadUrl(_urls[index]); } } @override Widget build(BuildContext context) { return MaterialApp( debugShowCheckedModeBanner: false, home: Scaffold( body: SafeArea( child: WebView( initialUrl: _urls[_selectedIndex], javascriptMode: JavascriptMode.unrestricted, onWebViewCreated: (controller) { _webViewController = controller; // 初始化控制器 }, ), ), bottomNavigationBar: BottomNavigationBar( items: const <BottomNavigationBarItem>[ BottomNavigationBarItem( icon: Icon(Icons.home), label: 'Home', ), BottomNavigationBarItem( icon: Icon(Icons.stacked_bar_chart_outlined), label: 'Status', ), ], currentIndex: _selectedIndex, selectedItemColor: Colors.amber[800], onTap: _onItemTapped, ), ), ); } }
关键说明
WebViewController是控制WebView加载、刷新、前进后退等操作的核心类,通过onWebViewCreated获取实例后,就能主动调用loadUrl方法切换页面- 在
_onItemTapped中,无论点击的是新项还是当前项,都会调用loadUrl,这样点击Home时会重新加载首页,实现刷新效果
内容的提问来源于stack exchange,提问作者RavenGaming
相关产品推荐
相关产品推荐

