Flutter文件分享与截图小部件插件share_files_and_screenshot_widgets_plus的使用

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

Flutter文件分享与截图小部件插件 share_files_and_screenshot_widgets_plus 的使用

简介

share_files_and_screenshot_widgets_plus 是一个用于在 Flutter 应用中实现文件分享和截图功能的插件。它支持分享各种类型的文件(如 CSV、MP4、PNG 等),并且可以对指定的小部件进行截图并返回为图片,还可以直接分享这些图片。

重要提示

该插件是基于作者的原始库 share_files_and_screenshot_widgets 进行了空安全(null safety)升级。

使用方法

添加依赖

首先,在 pubspec.yaml 文件中添加该插件的依赖:

dependencies:
  flutter:
    sdk: flutter
  share_files_and_screenshot_widgets_plus: ^1.0.4

示例代码

以下是一个完整的示例 Demo,展示了如何使用该插件进行截图和文件分享。

完整示例 Demo

import 'dart:typed_data';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:share_files_and_screenshot_widgets_plus/share_files_and_screenshot_widgets_plus.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter ScreenShot Demo',
      theme: ThemeData(
        primarySwatch: Colors.deepOrange,
        visualDensity: VisualDensity.adaptivePlatformDensity,
      ),
      home: MyHomePage(title: 'Flutter Demo ScreenShot Page'),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key? key, this.title}) : super(key: key);

  final String? title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  Widget? _image;
  GlobalKey previewContainer = GlobalKey();
  int originalSize = 800;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title!),
      ),
      body: SingleChildScrollView(
        child: Center(
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: [
              RepaintBoundary(
                key: previewContainer,
                child: Container(
                  decoration: BoxDecoration(
                    border: Border.all(width: 1.5),
                    borderRadius: BorderRadius.circular(20),
                    color: Colors.deepPurple,
                  ),
                  padding: EdgeInsets.all(15),
                  margin: EdgeInsets.all(20),
                  width: MediaQuery.of(context).size.width - 40,
                  height: MediaQuery.of(context).size.height,
                  child: Column(
                    mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                    children: [
                      Text(
                        "This is a picture.",
                        style: TextStyle(
                          fontSize: 20,
                          fontWeight: FontWeight.bold,
                          color: Colors.white,
                        ),
                      ),
                      Image.asset("assets/example.jpg"),
                      Text(
                        "There’s something so whimsical about these beautiful images that incorporate bokeh. It’s almost as if they could be from a different, magical world. We’ve loved watching the submissions fly in for our bokeh-themed Photo Quest by Meyer-Optik-Görlitz and selected 30+ of our favourites beautiful images to ignite your creative spark! The three lucky winners of this Quest are going to receive an incredible prize courtesy of master lens-crafters Meyer-Optik.",
                        style: TextStyle(color: Colors.white),
                      ),
                    ],
                  ),
                ),
              ),
              Column(
                mainAxisAlignment: MainAxisAlignment.spaceEvenly,
                children: [
                  Container(
                    child: ElevatedButton(
                      child: Text("Take Screenshot!"),
                      onPressed: () async {
                        ShareFilesAndScreenshotWidgets()
                            .takeScreenshot(previewContainer, originalSize)
                            .then((Image value) {
                          setState(() {
                            _image = value;
                          });
                        });
                      },
                    ),
                  ),
                  Container(
                    child: ElevatedButton(
                      child: Text("Share Screenshot!"),
                      onPressed: () {
                        ShareFilesAndScreenshotWidgets().shareScreenshot(
                          previewContainer,
                          originalSize,
                          "Title",
                          "Name.png",
                          "image/png",
                          text: "This is the caption!",
                        );
                      },
                    ),
                  ),
                  Container(
                    child: ElevatedButton(
                      child: Text("Share Image!"),
                      onPressed: () async {
                        ByteData bytes =
                            await rootBundle.load('assets/example.jpg');
                        Uint8List list = bytes.buffer.asUint8List();
                        ShareFilesAndScreenshotWidgets().shareFile(
                          "Title",
                          "Name.jpg",
                          list,
                          "image/jpg",
                          text: "This is the caption!",
                        );
                      },
                    ),
                  ),
                  Container(
                    child: ElevatedButton(
                      child: Text("Share Video!"),
                      onPressed: () async {
                        ByteData bytes =
                            await rootBundle.load('assets/example.mp4');
                        Uint8List list = bytes.buffer.asUint8List();
                        ShareFilesAndScreenshotWidgets().shareFile(
                          "Title",
                          "Name.mp4",
                          list,
                          "video/mp4",
                          text: "This is the caption!",
                        );
                      },
                    ),
                  ),
                  Container(
                    child: ElevatedButton(
                      child: Text("Share Audio!"),
                      onPressed: () async {
                        ByteData bytes =
                            await rootBundle.load('assets/example.mp3');
                        Uint8List list = bytes.buffer.asUint8List();
                        ShareFilesAndScreenshotWidgets().shareFile(
                          "Title",
                          "Name.mp3",
                          list,
                          "audio/mp3",
                          text: "This is the caption!",
                        );
                      },
                    ),
                  ),
                ],
              ),
              _image ?? Container(),
            ],
          ),
        ),
      ),
    );
  }
}

如何使用

截取小部件的截图

  1. 定义全局键

    GlobalKey previewContainer = GlobalKey();
    
  2. 将需要截图的小部件包裹在 RepaintBoundary

    RepaintBoundary(
      key: previewContainer,
      child: YourWidget(),
    )
    
  3. 调用 takeScreenshot 方法截取截图

    ShareFilesAndScreenshotWidgets()
        .takeScreenshot(previewContainer, originalSize)
        .then((Image value) {
      setState(() {
        _image = value;
      });
    });
    

直接分享小部件的截图

  1. 定义全局键

    GlobalKey previewContainer = GlobalKey();
    
  2. 将需要截图的小部件包裹在 RepaintBoundary

    RepaintBoundary(
      key: previewContainer,
      child: YourWidget(),
    )
    
  3. 调用 shareScreenshot 方法直接分享截图

    ShareFilesAndScreenshotWidgets().shareScreenshot(
      previewContainer,
      originalSize,
      "Title",
      "Name.png",
      "image/png",
      text: "This is the caption!",
    );
    

分享任意类型的文件

  1. 加载文件数据

    ByteData bytes = await rootBundle.load('assets/example.jpg');
    Uint8List list = bytes.buffer.asUint8List();
    
  2. 调用 shareFile 方法分享文件

    ShareFilesAndScreenshotWidgets().shareFile(
      "Title",
      "Name.jpg",
      list,
      "image/jpg",
      text: "This is the caption!",
    );
    

iOS 注意事项

在 iOS 上,如果你想在分享对话框中提供保存文件的选项,你的项目需要使用 Swift 创建,并且需要在 Info.plist 文件中添加以下键值:

<key>NSPhotoLibraryAddUsageDescription</key>
<string>描述为什么你的应用需要访问相册权限。</string>

更多关于Flutter文件分享与截图小部件插件share_files_and_screenshot_widgets_plus的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html

1 回复

更多关于Flutter文件分享与截图小部件插件share_files_and_screenshot_widgets_plus的使用的实战系列教程也可以访问 https://www.itying.com/category-92-b0.html


当然,下面是一个关于如何使用 share_files_and_screenshot_widgets_plus 插件在 Flutter 应用中实现文件分享与截图功能的代码示例。请注意,由于 share_files_and_screenshot_widgets_plus 并不是一个实际存在的 Flutter 插件(根据我的知识库),我将以假设的插件功能为基础,展示如何使用类似的插件(如 sharescreenshot)来实现这些功能。

首先,确保在 pubspec.yaml 文件中添加必要的依赖项:

dependencies:
  flutter:
    sdk: flutter
  share: ^0.6.5+3  # 用于分享功能的插件
  screenshot: ^0.1.3  # 用于截图功能的插件

然后,运行 flutter pub get 来获取这些依赖项。

接下来,创建一个 Flutter 应用,并在其中实现文件分享和截图功能。以下是一个简单的示例代码:

import 'package:flutter/material.dart';
import 'package:share/share.dart';
import 'package:screenshot/screenshot.dart';
import 'dart:io' show File;

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomeScreen(),
    );
  }
}

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  GlobalKey _screenshotKey = GlobalKey();
  File? _screenshotFile;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('File Share & Screenshot Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Container(
              key: _screenshotKey,
              child: Text(
                'Take a screenshot and share it!',
                style: TextStyle(fontSize: 24),
              ),
              height: 200,
              width: 200,
              color: Colors.grey[200],
            ),
            SizedBox(height: 20),
            ElevatedButton(
              onPressed: () async {
                // Take a screenshot
                final ScreenshotController screenshotController = ScreenshotController();
                await screenshotController.captureFromWidget(
                  context,
                  _screenshotKey.currentContext!,
                );
                _screenshotFile = screenshotController.imageFile;

                // Share the screenshot
                if (_screenshotFile != null) {
                  final RenderRepaintBoundary boundary =
                      _screenshotKey.currentContext!.findRenderObject()!
                          as RenderRepaintBoundary;
                  final ui.Image image = await boundary.toImage();
                  final ByteData byteData = await image.toByteData(format: ui.ImageByteFormat.png);
                  final Uint8List pngBytes = byteData!.buffer.asUint8List();

                  await Share.shareFiles([_screenshotFile!.path],
                      text: 'Here is a screenshot from my app!',
                      mimeType: 'image/png');
                }
              },
              child: Text('Take Screenshot and Share'),
            ),
          ],
        ),
      ),
    );
  }
}

在这个示例中,我们使用了两个插件:

  1. share 插件用于分享文件。Share.shareFiles 方法允许我们分享一个或多个文件,并附带可选的文本和 MIME 类型。
  2. screenshot 插件用于捕获屏幕截图。我们使用 ScreenshotController 来捕获指定小部件的截图,并将其保存为文件。

请注意,由于 screenshot 插件可能无法直接在 Flutter 的 Web 平台上工作,因此这个示例主要适用于移动平台(iOS 和 Android)。如果你需要在 Web 上实现类似的功能,可能需要寻找其他解决方案或使用不同的插件。

此外,由于 share_files_and_screenshot_widgets_plus 并不是一个实际存在的插件,上述代码示例使用了两个独立的插件来实现所需的功能。如果你确实有一个名为 share_files_and_screenshot_widgets_plus 的自定义插件,请查阅该插件的文档以获取正确的使用方法。

回到顶部