copy method

Future<void> copy({
  1. String? text,
  2. SimpleFileFormat? format,
  3. Uint8List? data,
})

Stores the provided text or data on the Clipboard.

Implementation

Future<void> copy({
  String? text,
  SimpleFileFormat? format,
  Uint8List? data,
}) async {
  if (text != null) {
    await Clipboard.setData(ClipboardData(text: text));
  } else if (data != null && format != null) {
    final clipboard = SystemClipboard.instance;
    if (clipboard == null) {
      return;
    }

    String? extension =
        (format.mimeTypes?.lastOrNull ?? format.fallbackFormats.lastOrNull)
            ?.split('/')
            .last;
    extension ??= '.bin';

    final String suggestedName =
        '${DateTime.now().millisecondsSinceEpoch}.$extension';

    // Web's Clipboard API support only `text/plain`, `text/html` and
    // `image/png`, thus always try to encode image as PNG.
    if (isWeb) {
      try {
        final Codec decoded = await instantiateImageCodec(data);
        final FrameInfo frame = await decoded.getNextFrame();

        try {
          final ByteData? png = await frame.image.toByteData(
            format: ImageByteFormat.png,
          );

          if (png != null) {
            final item = DataWriterItem(suggestedName: suggestedName);
            item.add(
              Formats.png(
                png.buffer.asUint8List(png.offsetInBytes, png.lengthInBytes),
              ),
            );
            await clipboard.write([item]);
          }
        } finally {
          // This object must be disposed by the recipient of the frame info.
          frame.image.dispose();
        }

        return;
      } catch (e) {
        rethrow;
      }
    }

    final item = DataWriterItem(suggestedName: suggestedName);
    item.add(format(data));
    await clipboard.write([item]);
  }
}