Flutter macOS WebView集成插件macos_webview_kit的使用

发布于 1周前 作者 itying888 来自 Flutter

Flutter macOS WebView集成插件macos_webview_kit的使用

[0.0.3]

简介

  • Flutter与macOS系统的WebView插件兼容,可以像在iOS系统中使用WKWebView一样平滑。在Flutter macOS项目中,WebView的打开(传递URL)和关闭是通过channel实现的。

配置 entitlements 文件

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>com.apple.security.app-sandbox</key>
	<true/>
	<key>com.apple.security.cs.allow-jit</key>
	<true/>
	<key>com.apple.security.network.server</key>
	<true/>
	<key>com.apple.security.network.client</key>
    <true/>
</dict>
</plist>

导入

import 'package:macos_webview_kit/macos_webview_kit.dart';

使用

打开

MacosWebviewKit().openWebView(urlString: "https://www.sohu.com");

关闭

MacosWebviewKit().closeWebView();

显示

MacosWebviewKit().showWebView();

隐藏

MacosWebviewKit().hideWebView();

效果

效果

完整示例

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

import 'package:flutter/services.dart';
import 'package:macos_webview_kit/macos_webview_kit.dart';

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

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

  [@override](/user/override)
  State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
  String _platformVersion = 'Unknown';
  final _macosWebviewKitPlugin = MacosWebviewKit();

  [@override](/user/override)
  void initState() {
    super.initState();
    initPlatformState();
  }

  // 平台消息是异步的,所以我们初始化在一个异步方法中。
  Future<void> initPlatformState() async {
    String platformVersion;
    // 平台消息可能会失败,所以我们使用try/catch PlatformException。
    // 我们还处理消息可能返回null的情况。
    try {
      platformVersion = await _macosWebviewKitPlugin.getPlatformVersion() ?? 'Unknown platform version';
    } on PlatformException {
      platformVersion = 'Failed to get platform version.';
    }

    // 如果小部件从树中被移除,而异步平台消息还在飞行中,我们想丢弃回复而不是调用setState来更新我们的不存在的外观。
    if (!mounted) return;

    setState(() {
      _platformVersion = platformVersion;
    });
  }

  Future<void> openWebView1() async {
    await _macosWebviewKitPlugin.openWebView(urlString: "https://www.sohu.com");
  }

  Future<void> openWebView2() async {
    await _macosWebviewKitPlugin.openWebView(urlString: "https://www.baidu.com");
  }

  Future<void> closeWebView() async {
    await _macosWebviewKitPlugin.closeWebView();
  }

  [@override](/user/override)
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: const Text('插件示例应用'),
        ),
        body: Center(
          child: Column(
            children: [
              Text('运行在: $_platformVersion\n'),
              const SizedBox(height: 10,),
              Row(
                mainAxisAlignment: MainAxisAlignment.spaceAround,
                children: [
                  ElevatedButton(onPressed: () => openWebView1(), child: const Text("打开webView1")),
                  ElevatedButton(onPressed: () => openWebView2(), child: const Text("打开webView2")),
                  ElevatedButton(onPressed: () => closeWebView(), child: const Text("关闭webView")),
                ],
              )
            ],
          ),
        ),
      ),
    );
  }
}

更多关于Flutter macOS WebView集成插件macos_webview_kit的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter macOS WebView集成插件macos_webview_kit的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,以下是一个关于如何在Flutter macOS应用中集成并使用macos_webview_kit插件的示例代码。这个插件允许你在Flutter应用中嵌入一个WebView组件。

首先,确保你已经在你的pubspec.yaml文件中添加了macos_webview_kit依赖:

dependencies:
  flutter:
    sdk: flutter
  macos_webview_kit: ^0.x.x  # 请替换为最新版本号

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

接下来,你需要配置你的Info.plist文件(对于macOS应用,这通常是Runner/Info.plist),确保应用有权限访问网络。这通常不需要额外的配置,但如果你的应用需要访问特定的URL模式,你可能需要添加相应的NSAppTransportSecurity设置。

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

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter WebView Example',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: WebViewExample(),
    );
  }
}

class WebViewExample extends StatefulWidget {
  @override
  _WebViewExampleState createState() => _WebViewExampleState();
}

class _WebViewExampleState extends State<WebViewExample> {
  late WebViewController _controller;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('WebView Example'),
      ),
      body: WebView(
        initialUrl: 'https://flutter.dev',
        javascriptMode: JavascriptMode.unrestricted,
        onWebViewCreated: (WebViewController webViewController) {
          _controller = webViewController;
        },
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: () async {
          // 示例:加载一个新的URL
          await _controller.loadUrl('https://google.com');
        },
        tooltip: 'Load another page',
        child: Icon(Icons.arrow_forward),
      ),
    );
  }
}

在这个示例中,我们创建了一个简单的Flutter应用,其中包含一个WebView组件。WebView组件的initialUrl属性设置了初始加载的URL。onWebViewCreated回调允许我们获取WebViewController实例,以便在后续操作中控制WebView(例如加载新的URL)。

请注意,macos_webview_kit插件的具体API和用法可能会随着版本的更新而变化,因此请查阅最新的官方文档和示例代码以确保兼容性和最佳实践。

此外,由于Flutter和插件生态的不断变化,确保你使用的Flutter SDK和插件版本是兼容的,并且在开发过程中定期更新依赖项以获取最新的功能和修复。

回到顶部