如何从用户输入的字符串加载网页

huangapple go评论57阅读模式
英文:

How to load a web page from user input string

问题

我刚开始学习Flutter,正在使用webview。我创建了一个应用程序,从文本字段中获取用户输入的字符串,并在按下按钮时将其加载到webview小部件中。但是当单击按钮时,webview小部件不会更新。以下是代码:

import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebviewScreen extends StatefulWidget {
  const WebviewScreen({Key? key});

  @override
  State<WebviewScreen> createState() => _WebviewScreenState();
}

class _WebviewScreenState extends State<WebviewScreen> {
  TextEditingController urlController = TextEditingController();
  WebViewController? webController;
  String url = 'https://google.com';

  Future<void> buttonPressed() async {
    setState(() {
      url = urlController.text;
    });
    await webController?.loadUrl(url);
  }

  @override
  void initState() {
    urlController.text = 'https://';
    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: WebView(
                initialUrl: url,
                onWebViewCreated: (controller) {
                  webController = controller;
                },
              ),
            )
          ],
        ),
      ),
    );
  }
}

我在iOS模拟器上运行这个应用。

webview_flutter版本:4.2.1

英文:

I'm new to learning flutter and am working on webview. I have created an application that takes in a user input string from a textfield and loads it in a webview widget when a button is pressed. But the webview widget doesn't update when the button is clicked. Here's the code:

import &#39;package:flutter/material.dart&#39;;
import &#39;package:webview_flutter/webview_flutter.dart&#39;;

class WebviewScreen extends StatefulWidget {
  const WebviewScreen({super.key});

  @override
  State&lt;WebviewScreen&gt; createState() =&gt; _WebviewScreenState();
}

class _WebviewScreenState extends State&lt;WebviewScreen&gt; {
  TextEditingController urlController = TextEditingController();
  WebViewController webController = WebViewController();
  String url = &#39;https://google.com&#39;;

  Future&lt;void&gt; buttonPressed() async {
    setState(() {
      url = urlController.text;
    });
    await webController.loadHtmlString(url);
  }

  @override
  void initState() {
    urlController.text = &#39;https://&#39;;
    webController.loadRequest(Uri.parse(url));
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text(&#39;Webview App&#39;),
      ),
      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: &#39;Enter URL&#39;,
                      ),
                    ),
                  ),
                ),
                TextButton(
                  onPressed: buttonPressed,
                  child: const Text(
                    &#39;Go&#39;,
                    style: TextStyle(fontSize: 25),
                  ),
                ),
              ],
            ),
            const SizedBox(height: 70),
            SizedBox(
              height: 500,
              width: 350,
              child: WebViewWidget(
                controller: webController,
              ),
            )
          ],
        ),
      ),
    );
  }
}

I am running this on the iOS simulator.

webview_flutter version: 4.2.1

答案1

得分: 1

你在按钮点击时加载HTML字符串,所以没有加载WebView,而是加载正常的HTML字符串。你需要使用 loadRequest() 而不是 loadHtmlString()

Future<void> buttonPressed() async {
    setState(() {
      url = urlController.text;
    });
    // await webController.loadHtmlString(url);    // 移除这行
    await webController.loadRequest(Uri.parse(url)); // 添加这行
}
英文:

You are load html string on button click that's why not load webview its loading normal HTML string.You need to used loadRequest() instead of loadHtmlString().

Future&lt;void&gt; buttonPressed() async {
    setState(() {
      url = urlController.text;
    });
    // await webController.loadHtmlString(url);    // remove this line
    await webController.loadRequest(Uri.parse(url)); // add this line
  }

答案2

得分: 0

改变buttonPressed()如下:

Future<void> buttonPressed() async {
    setState(() {
        url = urlController.text;
    });
    await webController.loadRequest(Uri.parse(url));
}
英文:

change the buttonPressed() as below

Future&lt;void&gt; buttonPressed() async {
    setState(() {
      url = urlController.text;
    });
    await webController.loadRequest(Uri.parse(url));
  }

huangapple
  • 本文由 发表于 2023年6月5日 13:22:40
  • 转载请务必保留本文链接:https://go.coder-hub.com/76403659.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定