flutter-plugins icon indicating copy to clipboard operation
flutter-plugins copied to clipboard

pasteboard.image: when system clipboard content changed, then it will crash

Open function2000 opened this issue 6 months ago • 0 comments

It is OK to get the image when there is image content in the system clipboard, but when I change the content, like I make another screenshot, then I cannot get the updated image, and it will crash my app.

Please help to check and solve it.

Thanks a lot!

Below is my code which is used together with Flutter_quill

Future _handlePasteImage() async { try { Uint8List? imageBytes = await Pasteboard.image;

  if (imageBytes == null || imageBytes.isEmpty) {
    debugPrint("no valid pic");
    return;
  }

  
  final decodedImage = await decodeImageFromList(imageBytes);
  if (decodedImage.width <= 0 || decodedImage.height <= 0) {
    debugPrint("no valid pic");
    return;
  }


  final dir = await getApplicationDocumentsDirectory();
  final fileName = 'pasted_${DateTime.now().millisecondsSinceEpoch}.png';
  final file = File('${dir.path}/$fileName');

  await file.writeAsBytes(imageBytes); 
  debugPrint("saved: ${file.path}");


  final imageUrl = file.path;
  final selection = Get.find<NoteViewController>().quill_controller.selection;
  final index = selection.baseOffset < 0 ? 0 : selection.baseOffset;

  Get.find<NoteViewController>().quill_controller.document.insert(index, BlockEmbed.image(imageUrl));
  Get.find<NoteViewController>().quill_controller.updateSelection(
    TextSelection.collapsed(offset: index + 1),
    ChangeSource.local,
  );
} catch (e, stack) {
  debugPrint("error: $e");
  debugPrint("$stack");
  if (mounted) {
    ScaffoldMessenger.of(context).showSnackBar(
      const SnackBar(content: Text("error")),
    );
  }
}

}

function2000 avatar May 25 '25 05:05 function2000