Flutter内嵌网页视图插件zikzak_inappwebview的使用

Flutter内嵌网页视图插件 zikzak_inappwebview 的使用

简介

zikzak_inappwebview 是一个Flutter插件,允许你在应用中添加内联WebView、无头WebView和打开应用内浏览器窗口。它是原版 flutter_inappwebview 插件的一个分支。

要求

  • Dart SDK: >=2.17.0 <4.0.0
  • Flutter: >=3.0.0
  • Android:
    • minSdkVersion >= 19
    • compileSdk >= 34
    • AGP版本 >= 7.3.0
    • 支持 androidx
  • iOS 9.0+:
    • --ios-language swift
    • Xcode版本 >= 14.3
  • MacOS 10.11+: Xcode版本 >= 14.3

安装

在你的 pubspec.yaml 文件中添加 zikzak_inappwebview 作为依赖项:

dependencies:
  zikzak_inappwebview: ^1.0.0

Web支持安装

为了在Web平台上正常工作,你需要将 web_support.js 文件添加到 web/index.html 文件的 <head> 标签中:

<head>
    <!-- ... -->
    <script type="application/javascript" src="/assets/packages/zikzak_inappwebview_web/assets/web/web_support.js" defer></script>
    <!-- ... -->
</head>

示例代码

以下是一个完整的示例代码,展示了如何使用 zikzak_inappwebview 插件来创建不同的WebView场景:

import 'dart:async';

import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:zikzak_inappwebview/zikzak_inappwebview.dart';

import 'package:zikzak_inappwebview_example/chrome_safari_browser_example.screen.dart';
import 'package:zikzak_inappwebview_example/headless_in_app_webview.screen.dart';
import 'package:zikzak_inappwebview_example/in_app_webiew_example.screen.dart';
import 'package:zikzak_inappwebview_example/in_app_browser_example.screen.dart';
import 'package:zikzak_inappwebview_example/web_authentication_session_example.screen.dart';
import 'package:pointer_interceptor/pointer_interceptor.dart';

final localhostServer = InAppLocalhostServer(documentRoot: 'assets');
WebViewEnvironment? webViewEnvironment;

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();

  if (!kIsWeb && defaultTargetPlatform == TargetPlatform.windows) {
    final availableVersion = await WebViewEnvironment.getAvailableVersion();
    assert(availableVersion != null,
        'Failed to find an installed WebView2 runtime or non-stable Microsoft Edge installation.');

    webViewEnvironment = await WebViewEnvironment.create(
        settings: WebViewEnvironmentSettings(userDataFolder: 'custom_path'));
  }

  if (!kIsWeb && defaultTargetPlatform == TargetPlatform.android) {
    await InAppWebViewController.setWebContentsDebuggingEnabled(kDebugMode);
  }

  runApp(MyApp());
}

PointerInterceptor myDrawer({required BuildContext context}) {
  var children = [
    ListTile(
      title: Text('InAppWebView'),
      onTap: () {
        Navigator.pushReplacementNamed(context, '/');
      },
    ),
    ListTile(
      title: Text('InAppBrowser'),
      onTap: () {
        Navigator.pushReplacementNamed(context, '/InAppBrowser');
      },
    ),
    ListTile(
      title: Text('ChromeSafariBrowser'),
      onTap: () {
        Navigator.pushReplacementNamed(context, '/ChromeSafariBrowser');
      },
    ),
    ListTile(
      title: Text('WebAuthenticationSession'),
      onTap: () {
        Navigator.pushReplacementNamed(context, '/WebAuthenticationSession');
      },
    ),
    ListTile(
      title: Text('HeadlessInAppWebView'),
      onTap: () {
        Navigator.pushReplacementNamed(context, '/HeadlessInAppWebView');
      },
    ),
  ];

  if (kIsWeb) {
    children = [
      ListTile(
        title: Text('InAppWebView'),
        onTap: () {
          Navigator.pushReplacementNamed(context, '/');
        },
      )
    ];
  } else if (defaultTargetPlatform == TargetPlatform.macOS) {
    children = [
      ListTile(
        title: Text('InAppBrowser'),
        onTap: () {
          Navigator.pushReplacementNamed(context, '/');
        },
      ),
      ListTile(
        title: Text('WebAuthenticationSession'),
        onTap: () {
          Navigator.pushReplacementNamed(context, '/WebAuthenticationSession');
        },
      ),
      ListTile(
        title: Text('HeadlessInAppWebView'),
        onTap: () {
          Navigator.pushReplacementNamed(context, '/HeadlessInAppWebView');
        },
      ),
    ];
  } else if (defaultTargetPlatform == TargetPlatform.windows ||
      defaultTargetPlatform == TargetPlatform.linux) {
    children = [
      ListTile(
        title: Text('InAppWebView'),
        onTap: () {
          Navigator.pushReplacementNamed(context, '/');
        },
      ),
      ListTile(
        title: Text('InAppBrowser'),
        onTap: () {
          Navigator.pushReplacementNamed(context, '/InAppBrowser');
        },
      ),
      ListTile(
        title: Text('HeadlessInAppWebView'),
        onTap: () {
          Navigator.pushReplacementNamed(context, '/HeadlessInAppWebView');
        },
      ),
    ];
  }
  return PointerInterceptor(
    child: Drawer(
      child: ListView(
        padding: EdgeInsets.zero,
        children: <Widget>[
          DrawerHeader(
            child: Text('zikzak_inappwebview example'),
            decoration: BoxDecoration(
              color: Colors.blue,
            ),
          ),
          ...children
        ],
      ),
    ),
  );
}

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

class _MyAppState extends State<MyApp> {
  @override
  void initState() {
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    if (kIsWeb) {
      return MaterialApp(initialRoute: '/', routes: {
        '/': (context) => InAppWebViewExampleScreen(),
      });
    }
    if (defaultTargetPlatform == TargetPlatform.macOS) {
      return MaterialApp(initialRoute: '/', routes: {
        '/': (context) => InAppBrowserExampleScreen(),
        '/HeadlessInAppWebView': (context) => HeadlessInAppWebViewExampleScreen(),
        '/WebAuthenticationSession': (context) => WebAuthenticationSessionExampleScreen(),
      });
    } else if (defaultTargetPlatform == TargetPlatform.windows ||
        defaultTargetPlatform == TargetPlatform.linux) {
      return MaterialApp(initialRoute: '/', routes: {
        '/': (context) => InAppWebViewExampleScreen(),
        '/InAppBrowser': (context) => InAppBrowserExampleScreen(),
        '/HeadlessInAppWebView': (context) => HeadlessInAppWebViewExampleScreen(),
      });
    }
    return MaterialApp(initialRoute: '/', routes: {
      '/': (context) => InAppWebViewExampleScreen(),
      '/InAppBrowser': (context) => InAppBrowserExampleScreen(),
      '/ChromeSafariBrowser': (context) => ChromeSafariBrowserExampleScreen(),
      '/HeadlessInAppWebView': (context) => HeadlessInAppWebViewExampleScreen(),
      '/WebAuthenticationSession': (context) => WebAuthenticationSessionExampleScreen(),
    });
  }
}

结论

zikzak_inappwebview 提供了强大的功能,可以让你轻松地在Flutter应用中嵌入网页视图。通过上述示例代码,你可以快速上手并实现各种WebView相关的功能。如果你有任何问题或需要进一步的帮助,请参考官方文档或查看贡献者列表以获取更多帮助。


更多关于Flutter内嵌网页视图插件zikzak_inappwebview的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter内嵌网页视图插件zikzak_inappwebview的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,我可以为你提供一个关于如何在Flutter中使用zikzak_inappwebview插件来嵌入网页视图的代码示例。zikzak_inappwebview是一个功能强大的Flutter插件,允许你在应用中嵌入和控制WebView。

首先,你需要在你的pubspec.yaml文件中添加zikzak_inappwebview依赖:

dependencies:
  flutter:
    sdk: flutter
  zikzak_inappwebview: ^2.5.0+10  # 请注意版本号,使用最新版本

然后运行flutter pub get来安装依赖。

接下来,你可以在你的Flutter应用中创建一个包含WebView的页面。以下是一个简单的示例:

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

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('InAppWebView Example'),
        ),
        body: WebViewPage(),
      ),
    );
  }
}

class WebViewPage extends StatefulWidget {
  @override
  _WebViewPageState createState() => _WebViewPageState();
}

class _WebViewPageState extends State<WebViewPage> {
  InAppWebViewController? _webViewController;

  @override
  Widget build(BuildContext context) {
    return Column(
      children: <Widget>[
        Expanded(
          child: InAppWebView(
            initialUrlRequest: URLRequest(url: Uri.parse("https://www.example.com")),
            initialOptions: InAppWebViewGroupOptions(
              crossPlatform: InAppWebViewOptions(
                debuggingEnabled: true,
              ),
            ),
            onWebViewCreated: (InAppWebViewController controller) {
              _webViewController = controller;
            },
            onLoadStart: (InAppWebViewController controller, String url) {
              print("Started loading URL: $url");
            },
            onLoadStop: (InAppWebViewController controller, String url) async {
              print("Finished loading URL: $url");
              // Optionally, you can perform further actions here, like hiding a loading indicator.
            },
          ),
        ),
        ElevatedButton(
          onPressed: () async {
            if (_webViewController != null) {
              _webViewController!.goBack();
            }
          },
          child: Text('Go Back'),
        ),
        ElevatedButton(
          onPressed: () async {
            if (_webViewController != null) {
              _webViewController!.goForward();
            }
          },
          child: Text('Go Forward'),
        ),
        ElevatedButton(
          onPressed: () async {
            if (_webViewController != null) {
              _webViewController!.reload();
            }
          },
          child: Text('Reload'),
        ),
      ],
    );
  }

  @override
  void dispose() {
    super.dispose();
    _webViewController?.dispose();
  }
}

在这个示例中,我们创建了一个包含WebView的页面,并在页面上添加了几个按钮来控制WebView的行为(如返回、前进和重新加载)。

  1. InAppWebView组件用于嵌入网页视图。
  2. initialUrlRequest属性指定了初始加载的URL。
  3. onWebViewCreated回调用于获取WebView控制器,以便后续操作。
  4. onLoadStartonLoadStop回调分别用于监听网页开始加载和加载完成的事件。
  5. 几个按钮用于控制WebView的导航行为。

请确保你已经正确安装了zikzak_inappwebview插件,并且你的Flutter环境配置正确。如果你遇到任何问题,可以查看插件的官方文档或GitHub仓库以获取更多信息和帮助。

回到顶部