Clipboard.setData(ClipboardData(text: textToCopy));
is working fine on flutter web when visiting via desktop browsers, but is nonfunctional on mobile (iOS Chrome & Safari).
Are there any work arounds?
I've tried a few other packages besides the classic flutter services, but they all had the same issue.
I have also encountered the same issue but for reading text from the clipboard. Clipboard.getData(Clipboard.kTextPlain) does not work on Flutter web for iOS or Android browsers
However, I found a workaround that works for me that uses javascript.
I will paste my code here
pubspec.yaml - install the js package
js: ^0.6.4
index.html - defines a function here
function pasteFromClipboard() {
return window.navigator.clipboard.readText();
}
clipboard_helper.dart
import 'clipboard_helper_stub.dart'
if (dart.library.io) 'clipboard_helper_for_mobile.dart'
if (dart.library.html) 'clipboard_helper_for_web.dart';
class ClipboardHelper {
final ClipboardHelperImpl _helper;
ClipboardHelper() : _helper = ClipboardHelperImpl();
Future<String?> readTextFromClipboard() async {
return _helper.readTextFromClipboard();
}
}
abstract class ClipboardHelperBase {
Future<String?> readTextFromClipboard();
}
clipboard_helper_stub.dart
import 'clipboard_helper.dart';
class ClipboardHelperImpl extends ClipboardHelperBase {
@override
Future<String?> readTextFromClipboard() async {
throw Exception("Stub implementation");
}
}
clipboard_helper_for_mobile.dart
import 'clipboard_helper.dart';
import 'package:flutter/services.dart';
class ClipboardHelperImpl extends ClipboardHelperBase {
@override
Future<String?> readTextFromClipboard() async {
final clipboardData = await Clipboard.getData(Clipboard.kTextPlain);
final text = clipboardData?.text;
return text;
}
}
clipboard_helper_for_web.dart
import 'package:js/js.dart';
import 'clipboard_helper.dart';
import 'package:js/js_util.dart';
@JS('pasteFromClipboard')
external dynamic pasteFromClipboard();
class ClipboardHelperImpl extends ClipboardHelperBase {
@override
Future<String?> readTextFromClipboard() async {
final String? text = await promiseToFuture(
pasteFromClipboard(),
);
return text;
}
}
Conclusion - I hope this could help someone and wish that Clipboard.getData() could be fixed in the future but I am using this workaround for now which seems to work
Please note that the window.navigator.clipboard could be undefined as it requires a secure origin (HTTPS or localhost)
reference: navigator.clipboard is undefined
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With