我刚开始学习flutter,正在使用webview。我创建了一个应用程序,它从文本字段中接收用户输入字符串,并在按下按钮时将其加载到webview小部件中。但是当按钮被点击时webview小部件不会更新。代码如下:
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> {
TextEditingController urlController = TextEditingController();
WebViewController webController = WebViewController();
String url = 'https://google.com';
Future<void> buttonPressed() async {
setState(() {
url = urlController.text;
});
await webController.loadHtmlString(url);
}
@override
void initState() {
urlController.text = 'https://';
webController.loadRequest(Uri.parse(url));
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,
),
)
],
),
),
);
}
}
我在iOS模拟器上运行这个。
webview_flutter版本:4.2.1
2条答案
按热度按时间ghg1uchk1#
你是加载HTML字符串的按钮点击这就是为什么不加载webview其加载正常的HTML字符串。你需要使用
loadRequest()
而不是loadHtmlString()
。7d7tgy0s2#
将
buttonPressed()
更改如下