share method

Future<void> share(
  1. SnapchatMediaType mediaType, {
  2. ImageProvider<Object>? image,
  3. String? videoPath,
  4. SnapchatSticker? sticker,
  5. String? caption,
  6. String? attachmentUrl,
})

share shares Media to be sent in the Snapchat app. mediaType defines what type of background media is to be shared.

SnapchatMediaType.PHOTO requires image to be non null.

SnapchatMediaType.VIDEO requires videoUrl to be non null.

image is an ImageProvider instance

videoUrl is a String that contains an external url eg. https://domain.com/video.mp4/

SnapchatSticker is a SnapchatSticker instance

caption is a String no longer than 250 characters

attachmentUrl is a String that contains an external url eg. https://domain.com/

Implementation

Future<void> share(
  SnapchatMediaType mediaType, {
  ImageProvider<Object>? image,
  String? videoPath,
  SnapchatSticker? sticker,
  String? caption,
  String? attachmentUrl,
}) async {
  assert(caption != null ? caption.length <= 250 : true);

  Completer<File?> imageCompleter = new Completer<File?>();
  Completer<File?> videoCompleter = new Completer<File?>();

  if (mediaType == SnapchatMediaType.PHOTO) {
    assert(image != null);
    image!
        .resolve(new ImageConfiguration())
        .addListener(new ImageStreamListener((imageInfo, _) async {
      String path = (await getTemporaryDirectory()).path;
      ByteData? byteData =
          await imageInfo.image.toByteData(format: ImageByteFormat.png);
      ByteBuffer buffer = byteData!.buffer;

      File file = await new File('$path/image.png').writeAsBytes(
          buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));

      imageCompleter.complete(file);
    }));
  } else {
    imageCompleter.complete(null);
  }

  if (mediaType == SnapchatMediaType.VIDEO) {
    assert(videoPath != null);
    String path = (await getTemporaryDirectory()).path;
    ByteData byteData = await rootBundle.load(videoPath!);
    ByteBuffer buffer = byteData.buffer;

    File file = await new File('$path/video.mp4').writeAsBytes(
        buffer.asUint8List(byteData.offsetInBytes, byteData.lengthInBytes));

    videoCompleter.complete(file);
  } else {
    videoCompleter.complete(null);
  }

  File? imageFile = await imageCompleter.future;
  File? videoFile = await videoCompleter.future;

  await _channel.invokeMethod('sendMedia', <String, dynamic>{
    'mediaType':
        mediaType.toString().substring(mediaType.toString().indexOf('.') + 1),
    'imagePath': imageFile?.path,
    'videoPath': videoFile?.path,
    'sticker': sticker != null ? await sticker.toMap() : null,
    'caption': caption,
    'attachmentUrl': attachmentUrl
  });
}