如何在Flutter中添加Webview?

38

我知道可以将WebView添加为整个页面,但找不到任何示例代码来实现。我猜想可以使用PageView作为基础,但不确定如何调用本地Android WebView并将其添加到PageView中。

有人能指点一下吗?


https://codelabs.developers.google.com/codelabs/flutter-webview - Omkar76
11个回答

42
你可以使用 https://pub.dartlang.org/packages/webview_flutter
示例。
import 'package:webview_flutter/webview_flutter.dart';

return Scaffold(
      appBar: AppBar(
        title: const Text('Flutter WebView example'),
      ),
      body: const WebView(
        initialUrl: 'https://flutter.io',
        javascriptMode: JavascriptMode.unrestricted,
      ),
    );

这可能是最好的选择,不幸的是它仍处于开发者预览状态。 - 最白目
4
重要提示:安卓设备上无法显示键盘(请参见问题#19718)。如果您想在OAuth中使用此功能,这将是一个致命问题。如果您需要此功能,请投票支持该问题,或许它会被重新确定优先级,并在其当前里程碑(2019年10月)之前尽快修复。 - Matt

15

Flutter没有内置支持嵌入式WebViews的功能。关注问题730以获取更新。

您仍然可以在应用程序中显示Web内容,但必须使用插件系统离开Flutter环境。

如果只想打开浏览器,可以使用url_launcher Flutter插件。

如果要执行更高级的操作(例如不想要可见的地址栏),可以实现自定义的UIViewController (iOS示例) 和 Activity (Android示例),并使用插件 API启动它们。


1
还没有使用过这个,但它可能正在做这件事:https://pub.dartlang.org/packages/flutter_webview_plugin - Randal Schwartz

8
您可以使用下面的Dart插件来显示Webview。同时,您可以在此网址中找到Dart插件:https://pub.dartlang.org/packages/flutter_webview_plugin
new MaterialApp(
      routes: {
        "/": (_) => new WebviewScaffold(
          url: "https://www.google.com",
          appBar: new AppBar(
            title: new Text("Widget webview"),
          ),
        ),
      },
    );

2
在我看来,这个比webview_flutter更好用。它不会出现无法显示键盘的问题,而且当点击下拉菜单等等时,我也没有遇到webview_flutter造成的崩溃。 - AlvaroSantisteban

5

3

在 pubspec.yml 文件中添加依赖项:

webview_flutter: ^0.1.1

对于 ioS 应用,将以下密钥粘贴到 ios 项目文件夹内的 .plist 文件中

<key>io.flutter.embedded_views_preview</key><string>yes</string>
<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
    <key>NSAllowsArbitraryLoadsInWebContent</key>
    <true/>
</dict>

这是类代码:

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

class WebViewClass extends StatefulWidget {
  @override
  _WebViewClassState createState() => _WebViewClassState();
}

class _WebViewClassState extends State<WebViewClass> {
  Completer<WebViewController> _controller = Completer<WebViewController>();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('WebView'),
      ),
      body: WebView(
        initialUrl: 'https://google.com',
        onWebViewCreated: (WebViewController webViewController) {
          _controller.complete(webViewController);
        },
      ),
    );
  }
}

你好!感谢您的建议,但它仍然无法工作:不支持的操作:尝试在TargetPlatform.macOS上使用默认的webview实现,但没有默认实现。 - Sergei Eensalu

3
你可以使用Flutter WebView插件。这是插件的URL链接:https://pub.dartlang.org/packages/webview_flutter 带有CircularProgressIndicator的WebView。以下是一些屏幕截图:之前之后
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:webview_flutter/webview_flutter.dart';

class WebView extends StatefulWidget {
  @override
  _WebViewState createState() => _WebViewState();
}

class _WebViewState extends State<WebView> {

  final Completer<WebViewController> _controller =
      Completer<WebViewController>();

  num _stackToView = 1;

  void _handleLoad(String value) {
    setState(() {
      _stackToView = 0;
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          leading: Builder(builder: (BuildContext context) {
            return IconButton(
              icon: Icon(Icons.volume_up, color: Colors.black,),
              onPressed: () {
                Navigator.pop(context);
              },
            );
          }),
          backgroundColor: Colors.white10,
          elevation: 0,
        ),
        body: IndexedStack(
          index: _stackToView,
          children: [
            Column(
              children: <Widget>[
                Expanded(
                    child: WebView(
                  initialUrl: "https://www.google.co.in/",
                  javascriptMode: JavascriptMode.unrestricted,
                  onPageFinished: _handleLoad,
                  onWebViewCreated: (WebViewController webViewController) {
                    _controller.complete(webViewController);
                  },
                )),
              ],
            ),
            Container(
              child: Center(child: CircularProgressIndicator(),)
            ),
          ],
        ));
  }
}

2
截至2023年,包版本(webview_flutter: ^4.0.6)已有更新,使得WebViewWidget可以加载URL。要实现这一点,您可以从WebView控制器创建一个对象,然后利用WebView控制器中的'loadRequest'属性。
以下是示例:
class MyHomePage extends StatelessWidget {
  const MyHomePage({super.key});
  @override
  Widget build(BuildContext context) {
    WebViewController webViewController = WebViewController();

    return Scaffold(
        appBar: AppBar(),
        body: WebViewWidget(
            controller: webViewController
              ..loadRequest(Uri.parse('https://flutter.dev'))));
  }
}

2
您可以使用flutter_inappwebview插件。这是一个Flutter插件,允许您添加与小部件树集成的内联Web视图或打开应用内浏览器窗口!与其他Web视图插件相比,它提供了许多事件、方法和选项!
主要类:
  • InAppWebView:Flutter小部件,用于将内联本地WebView集成到Flutter小部件树中。在iOS上使用InAppWebView类,您需要通过在应用程序的Info.plist文件中添加一个布尔属性,并设置键io.flutter.embedded_views_preview和值YES来选择嵌入式视图预览。
  • ContextMenu:该类表示WebView上下文菜单。
  • HeadlessInAppWebView:代表无界面模式下的WebView的类。它可用于在后台运行WebView而不将InAppWebView附加到小部件树中。
  • InAppBrowser:使用本机WebView的应用内浏览器。
  • ChromeSafariBrowser:在Android上使用 Chrome Custom Tabs / 在iOS上使用SFSafariViewController的应用内浏览器。
  • InAppLocalhostServer:此类允许您在http://localhost:[port]/上创建一个简单的服务器。默认的port值为8080
  • CookieManager:此类实现了一个单例对象(共享实例),该对象管理WebView实例使用的Cookie。
  • HttpAuthCredentialDatabase:此类实现了一个单例对象(共享实例),该对象管理共享的HTTP身份验证凭据缓存。
  • WebStorageManager:此类实现了一个单例对象(共享实例),该对象管理WebView实例使用的Web存储。
这是一个展示WebView全屏显示的例子:
import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  runApp(new MyApp());
}

class MyApp extends StatefulWidget {
  @override
  _MyAppState createState() => new _MyAppState();
}

class _MyAppState extends State<MyApp> {
  InAppWebViewController _webViewController;

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('InAppWebView Example'),
        ),
        body: Container(
            child: Column(children: <Widget>[
              Expanded(
                child:InAppWebView(
                    initialUrl: "https://flutter.dev/",
                    initialOptions: InAppWebViewGroupOptions(
                        crossPlatform: InAppWebViewOptions(
                          debuggingEnabled: true,
                        )
                    ),
                    onWebViewCreated: (InAppWebViewController controller) {
                      _webViewController = controller;
                    },
                    onLoadStart: (InAppWebViewController controller, String url) {

                    },
                    onLoadStop: (InAppWebViewController controller, String url) {

                    },
                ),
              ),
            ])),
      ),
    );
  }
}

截图:

enter image description here


InAppWebView 有 10000 个未解决的问题... - Martin Berger

1

库: https://pub.dev/packages/webview_flutter

我的实现方式如下:

import 'package:webview_flutter/webview_flutter.dart';
...
return Scaffold(
      appBar: AppBar(toolbarHeight: 0),
      body: Builder(builder: (BuildContext context) {
        return WebView(
          initialUrl: 'https://flutter.dev/',
          javascriptMode: JavascriptMode.unrestricted,
          gestureNavigationEnabled: true,
          backgroundColor: const Color(0x00000000),
        );
      }),
    );

0

因为在Android 9中禁止使用'http'

您可以进行以下设置:

在您的android>app>src>main文件夹中导航到AndroidManifest.xml

   <application
    android:name="io.flutter.app.FlutterApplication"
    android:icon="@mipmap/ic_launcher"
    android:usesCleartextTraffic="true" />

Flutter WebView插件在Android 9上出现错误


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接