Flutter屏幕截图插件native_screenshot_widget的使用

Flutter屏幕截图插件native_screenshot_widget的使用

native_screenshot_widget 是一个用于Flutter应用中对特定Widget或WebView进行屏幕截图的插件。它允许开发者轻松地截取页面中的任意部分,并将其转换为图片格式。

使用方法

引入依赖

首先,在pubspec.yaml文件中添加native_screenshot_widget作为依赖:

dependencies:
  native_screenshot_widget: ^latest_version # 替换为最新版本号

然后执行flutter pub get来安装这个包。

示例代码

以下是一个完整的示例,展示了如何在Flutter应用程序中使用native_screenshot_widget插件对WebView和普通Flutter Widget进行截图。该例子还演示了如何将截图结果显示在一个对话框中。

main.dart

// ignore_for_file: use_build_context_synchronously

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

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

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

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'NativeScreenshot Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(title: 'NativeScreenshot'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  const MyHomePage({super.key, required this.title});

  final String title;

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  final webViewScreenshotController = NativeScreenshotController();
  final flutterWidgetScreenshotController = NativeScreenshotController();

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        backgroundColor: Theme.of(context).colorScheme.inversePrimary,
        title: Text(widget.title),
        actions: [
          Container(
            margin: const EdgeInsets.only(right: 24),
            child: PopupMenuButton<VoidCallback>(
              child: const Text('Menus'),
              onSelected: (call) {
                Future.delayed(const Duration(milliseconds: 300), call);
              },
              itemBuilder: (context) {
                return [
                  PopupMenuItem(
                    value: () => _takeScreenshot('WebView', webViewScreenshotController),
                    child: const Text('WebView Screenshot'),
                  ),
                  PopupMenuItem(
                    value: () => _takeScreenshot(
                        'Flutter Widget', flutterWidgetScreenshotController),
                    child: const Text('Flutter Widget Screenshot'),
                  ),
                ];
              },
            ),
          ),
        ],
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          const Text("WebView:"),
          Expanded(
            child: NativeScreenshot(
              controller: webViewScreenshotController,
              child: WebViewWidget(
                controller: WebViewController()
                  ..loadRequest(Uri.parse('https://flutter.dev')),
              ),
            ),
          ),
          const Text("Flutter Widget:"),
          Expanded(
            child: Container(
              margin: const EdgeInsets.all(8),
              child: NativeScreenshot(
                controller: flutterWidgetScreenshotController,
                child: Container(
                  width: double.infinity,
                  decoration: BoxDecoration(
                    color: Colors.grey.shade300,
                    borderRadius: BorderRadius.circular(16),
                  ),
                  child: SingleChildScrollView(
                    child: Column(
                      crossAxisAlignment: CrossAxisAlignment.center,
                      mainAxisAlignment: MainAxisAlignment.center,
                      children: [
                        Container(
                            height: 1,
                            width: double.infinity,
                            color: Colors.red),
                        const SizedBox(height: 24),
                        Text(
                          "Flutter Widget",
                          style: Theme.of(context).textTheme.titleLarge,
                        ),
                        Container(
                          width: 100,
                          height: 100,
                          color: Colors.blue,
                        ),
                        const SizedBox(height: 16),
                        ClipOval(
                          child: Container(
                            width: 100,
                            height: 100,
                            color: Colors.red,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }

  void _takeScreenshot(
    String type,
    NativeScreenshotController screenshotController,
  ) async {
    final list = (await Future.wait([
      1.0,
      0.5,
      0.1,
    ].map((scale) async {
      final bytes = await screenshotController.takeScreenshot(scale: scale);
      if (bytes != null) {}
      return MapEntry('Scale $scale', bytes);
    })))
        .where((e) => e.value != null);

    if (list.isNotEmpty) {
      showDialog(
        context: context,
        builder: (c) => AlertDialog(
          title: Text('Screenshot-$type'),
          content: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              for (var i = 0; i < list.length; i++)
                Flexible(
                  child: Container(
                    margin: EdgeInsets.only(top: i > 0 ? 16 : 0),
                    child: Column(
                      mainAxisSize: MainAxisSize.min,
                      crossAxisAlignment: CrossAxisAlignment.start,
                      children: [
                        Text(list.elementAt(i).key),
                        Flexible(
                          child: Image.memory(
                            list.elementAt(i).value!,
                            alignment: Alignment.center,
                            fit: BoxFit.contain,
                          ),
                        ),
                      ],
                    ),
                  ),
                ),
            ],
          ),
        ),
      );
    }
  }
}

在这个例子中,我们创建了一个包含两个部分的应用界面:一个是加载了网页的WebView,另一个是简单的Flutter Widget布局。通过点击右上角菜单按钮选择“WebView Screenshot”或“Flutter Widget Screenshot”,可以触发相应的截图操作,并将结果以不同缩放比例展示在一个弹出对话框内。

希望这段代码能帮助你理解如何在自己的项目里集成并使用native_screenshot_widget插件。如果有任何问题或者需要进一步的帮助,请随时提问!


更多关于Flutter屏幕截图插件native_screenshot_widget的使用的实战教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter屏幕截图插件native_screenshot_widget的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何在Flutter应用中使用native_screenshot_widget插件进行屏幕截图的示例代码。native_screenshot_widget是一个允许在Flutter应用中轻松捕获屏幕截图的插件。

首先,确保你的Flutter项目中已经添加了native_screenshot_widget依赖。你可以通过在pubspec.yaml文件中添加以下依赖来实现:

dependencies:
  flutter:
    sdk: flutter
  native_screenshot_widget: ^0.3.0  # 请检查最新版本号

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

接下来,你可以按照以下步骤在你的Flutter应用中使用native_screenshot_widget

  1. 导入插件

在你的Dart文件中导入native_screenshot_widget

import 'package:native_screenshot_widget/native_screenshot_widget.dart';
  1. 使用ScreenshotWidget

将你想要截图的区域包裹在ScreenshotWidget中。这里是一个简单的例子:

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

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('Screenshot Example'),
        ),
        body: Center(
          child: ScreenshotWidget(
            // 截图区域
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              children: <Widget>[
                Text(
                  'Hello, Flutter!',
                  style: TextStyle(fontSize: 24),
                ),
                SizedBox(height: 20),
                ElevatedButton(
                  onPressed: () async {
                    // 触发截图
                    final Uint8List imageBytes = await ScreenshotWidget.capture();
                    // 这里你可以将截图保存到文件或者显示
                    // 例如,显示截图(需要引入image库)
                    final imageProvider = MemoryImage(imageBytes);
                    showDialog(
                      context: context,
                      builder: (context) => AlertDialog(
                        content: Image.memory(imageBytes),
                      ),
                    );
                  },
                  child: Text('Take Screenshot'),
                ),
              ],
            ),
          ),
        ),
      ),
    );
  }
}

在上面的代码中,ScreenshotWidget包裹了一个简单的Column,其中包含一个Text和一个ElevatedButton。当用户点击按钮时,ScreenshotWidget.capture()方法会被调用,并返回一个包含截图数据的Uint8List。然后,这个截图数据被用来创建一个MemoryImage,并在一个对话框中显示。

  1. 运行应用

现在你可以运行你的Flutter应用,点击按钮来捕获屏幕截图并查看结果。

这个示例展示了如何使用native_screenshot_widget插件在Flutter应用中捕获屏幕截图。根据需求,你可以进一步处理截图数据,比如保存到设备存储或发送到服务器。

回到顶部