Flutter WebView点击按钮无法加载用户输入URL的问题求助
问题分析与解决
你的WebView点击按钮后不更新,核心问题有两个:
- 错误使用加载方法:你调用了
webController.loadHtmlString(url),但这个方法是用来加载HTML代码字符串的,不是加载URL的。加载URL应该用loadRequest(Uri.parse(url))。 - URL格式可能不合法:如果用户输入的URL没有
http://或https://前缀,Uri.parse会解析失败,导致WebView无法加载。
另外,setState(() { url = urlController.text; })其实是多余的,因为WebViewController的状态变化会直接同步到WebViewWidget,不需要通过更新url变量触发UI重建。
修正后的代码
import 'package:flutter/material.dart'; import 'package:webview_flutter/webview_flutter.dart'; class WebviewScreen extends StatefulWidget { const WebviewScreen({super.key}); @override State<WebviewScreen> createState() => _WebviewScreenState(); } class _WebviewScreenState extends State<WebviewScreen> { final TextEditingController urlController = TextEditingController(); final WebViewController webController = WebViewController(); Future<void> buttonPressed() async { String inputUrl = urlController.text.trim(); // 检查是否包含http/https前缀,没有则自动添加https if (!inputUrl.startsWith('http://') && !inputUrl.startsWith('https://')) { inputUrl = 'https://$inputUrl'; } // 使用loadRequest加载URL await webController.loadRequest(Uri.parse(inputUrl)); } @override void initState() { urlController.text = 'https://'; webController.loadRequest(const Uri.parse('https://google.com')); super.initState(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Webview App'), ), body: SingleChildScrollView( child: Column( children: [ Row( crossAxisAlignment: CrossAxisAlignment.baseline, textBaseline: TextBaseline.ideographic, children: [ Expanded( child: Container( margin: const EdgeInsets.symmetric(horizontal: 20), child: TextField( controller: urlController, keyboardType: TextInputType.url, decoration: const InputDecoration( labelText: 'Enter URL', ), ), ), ), TextButton( onPressed: buttonPressed, child: const Text( 'Go', style: TextStyle(fontSize: 25), ), ), ], ), const SizedBox(height: 70), SizedBox( height: 500, width: 350, child: WebViewWidget( controller: webController, ), ) ], ), ), ); } }
关键修改说明
- 替换
loadHtmlString为loadRequest(Uri.parse(inputUrl)),正确加载URL资源 - 添加URL前缀检查,自动补全
https://,避免因格式错误导致加载失败 - 移除多余的
setState调用,简化逻辑
内容的提问来源于stack exchange,提问作者Twisha Solgama
相关产品推荐
相关产品推荐

