dart 如何在webview_flutter中打开http站点?

m3eecexj  于 2023-09-28  发布在  Flutter
关注(0)|答案(2)|浏览(146)

我需要在flutter应用程序的webview中打开http站点,但在adnroid中无法正常工作。对于IOS,我在info.plist文件中添加了密钥,但我找不到Android的解决方案。有没有办法允许打开不安全的网站?
我正在使用webview_flutter
我试图添加以下xml文件,以允许不安全的网站,并提供它的路径AndroidManifest文件,但它没有工作。

android/app/src/main/res/xml/network_security_config.xml
<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true">
        <trust-anchors>
            <!-- You can add trusted certificates here if needed -->
        </trust-anchors>
    </base-config>
</network-security-config>

这是我的manifest文件:

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
package="com.example.webview_demo">

<uses-permission android:name="android.permission.INTERNET" />
<application
    android:name="${applicationName}"
    android:icon="@mipmap/ic_launcher"
    android:label="webview_demo"
    android:networkSecurityConfig="@xml/network_security_config"
    android:usesCleartextTraffic="true">
    <activity
        android:name=".MainActivity"
        android:configChanges="orientation|keyboardHidden|keyboard|screenSize|smallestScreenSize|locale|layoutDirection|fontScale|screenLayout|density|uiMode"
        android:exported="true"
        android:hardwareAccelerated="true"
        android:launchMode="singleTop"
        android:theme="@style/LaunchTheme"
        android:windowSoftInputMode="adjustResize">
        <!-- Specifies an Android theme to apply to this Activity as soon as
             the Android process has started. This theme is visible to the user
             while the Flutter UI initializes. After that, this theme continues
             to determine the Window background behind the Flutter UI. -->
        <meta-data
            android:name="io.flutter.embedding.android.NormalTheme"
            android:resource="@style/NormalTheme" />
        <intent-filter>
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
        </intent-filter>
    </activity>
    <!-- Don't delete the meta-data below.
         This is used by the Flutter tool to generate GeneratedPluginRegistrant.java -->
    <meta-data
        android:name="flutterEmbedding"
        android:value="2" />
</application>

我的webview代码:

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

class WebviewScreen extends StatefulWidget {
  final String url;

  const WebviewScreen({Key? key, required this.url}) : super(key: key);

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

class _WebviewScreenState extends State<WebviewScreen> {
  WebViewController? webViewController;

  @override
  void initState() {
    super.initState();
    loadWebView();
  }

  loadWebView() {
    webViewController = WebViewController()
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(Colors.white)
      ..setNavigationDelegate(
        NavigationDelegate(
          onPageStarted: (String url) {
            log('Page started loading: $url');
          },
          onProgress: (int progress) {
            log('WebView is loading (progress : $progress%)');
          },
          onPageFinished: (String url) {
            log('Page finished loading: $url');
          },
          onWebResourceError: (WebResourceError error) {
            log('Webview resource error $error');
          },
          onNavigationRequest: (NavigationRequest request) {
            if (request.url.contains("http:/")) {
              log("first redirection ${request.url}");
              return NavigationDecision.navigate;
            }
            return NavigationDecision.navigate;
          },
        ),
      )
      ..loadRequest(
        Uri.parse(widget.url),
      );
  }

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
        onWillPop: () async {
          return true;
        },
        child: Scaffold(
          appBar: AppBar(
            leading: const BackButton(),
            title: const Text('Webview'),
            centerTitle: true,
          ),
          body: SafeArea(
            bottom: false,
            child: Column(
              children: [
                Expanded(
                  child: WebViewWidget(
                    controller: webViewController!,
                  ),
                )
              ],
            ),
          ),
        ));
  }
}

enter code here
slwdgvem

slwdgvem1#

安卓系统

AndroidManifst.xml文件的标签application中添加一段代码

android:networkSecurityConfig="@xml/network_security_config"
android:usesCleartextTraffic="true"

res/xml目录下添加一个名为network_security_config.xml的文件,文件内容为

<?xml version="1.0" encoding="utf-8"?>
<network-security-config>
    <base-config cleartextTrafficPermitted="true" />
</network-security-config>

iOS

Info.plist文件的标签dict中添加一段代码

<key>NSAppTransportSecurity</key>  
<dict>  
    <key>NSAllowsArbitraryLoads</key><true/>  
</dict>
k3fezbri

k3fezbri2#

这可能是使用Flutter创建WebView的最佳/最简单的方法。
将包webview_flutter导入到项目中

import 'package:webview_flutter/webview_flutter.dart';

为webview创建一个类:

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

class WebViewContainer extends StatefulWidget {
  final String websiteURL;
  WebViewContainer({super.key, required this.websiteURL});

  @override
  State<StatefulWidget> createState() => _WebViewContainerState();
}

class _WebViewContainerState extends State<WebViewContainer> {
  final controller = WebViewController();

  @override
  Widget build(BuildContext context) {
    controller
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..loadRequest(Uri.parse(widget.websiteURL));

    return Scaffold(
      appBar: AppBar(title: Text("My Web View")),
      body: WebViewWidget(controller: controller),
    );
  }
}

然后在代码中随时调用它

Navigator.push(context,
     MaterialPageRoute(builder: (context) =>
         WebViewContainer(
            websiteURL:"https://stackoverflow.com")
 ));

如果您的版本以前低于19,请不要忘记在android/app/build.gradle中设置minSdkVersion

android {
    defaultConfig {
        minSdkVersion 19
    }
}

所有这些配置完成后,您就可以打开任何HTTPS网站了。但是,对于HTTP站点,还有一些额外的步骤。您可以在this StackOverflow post中阅读它们。

相关问题