如何从另一个屏幕将 url 传递到 WebViewController?

问题描述 投票:0回答:1

我正在尝试将 url 从另一个屏幕传递到 WebViewController,如下所示:

class WebPage extends StatelessWidget {
  WebPage({Key? key, required this.url}) : super(key: key);
  final String url;
  //static String url;

  // Create a WebView controller
  final _controller = WebViewController()
    ..setJavaScriptMode(JavaScriptMode.unrestricted)
    ..setNavigationDelegate(
      NavigationDelegate(
        onProgress: (int progress) {
          // print the loading progress to the console
          // you can use this value to show a progress bar if you want
          debugPrint("Loading: $progress%");
        },
        onPageStarted: (String url) {},
        onPageFinished: (String url) {},
        onWebResourceError: (WebResourceError error) {},
        onNavigationRequest: (NavigationRequest request) {
          return NavigationDecision.navigate;
        },
      ),
    )
    ..loadRequest(Uri.parse(url));
...

但是我收到错误:

The instance member 'url' can't be accessed in an initializer.

如果我将字符串 url 设置为静态,则此错误就会消失。但后来我又收到另一个错误:

'url' is a static field in the enclosing class. Fields initialized in a constructor can't be static.

那么如何正确地将 url 从另一个屏幕传递到 WebViewController 呢?

flutter dart webview
1个回答
0
投票

只需将最终的 _controller 代码移至构建函数中即可。 检查下面的代码例如:

class WebViewPage extends StatelessWidget {
  final String url;

  const WebViewPage({super.key, required this.url});

  @override
  Widget build(BuildContext context) {
    final WebViewController webViewController = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(const Color(0x00000000))
      ..setNavigationDelegate(
        NavigationDelegate(
          onProgress: (int progress) {
            // Update loading bar.
          },
          onPageStarted: (String url) {},
          onPageFinished: (String url) {},
          onWebResourceError: (WebResourceError error) {},
          onNavigationRequest: (NavigationRequest request) {
            return NavigationDecision.navigate;
          },
        ),
      )
      ..loadRequest(Uri.parse(url));

    return Scaffold(
      appBar: AppBar(title: const Text('WebView Example')),
      body: WebViewWidget(controller: webViewController),
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.