Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I monitor the clipboard in Flutter?

Tags:

flutter

I'm looking for a way to monitor the Clipboard in Flutter, all I could find relating to clipboard interaction on Flutter was: Clipboard class,

does anybody know how can I monitor the system clipboard for new items in Flutter, preferably using a plugin?

like image 396
dsilveira Avatar asked Jun 01 '18 16:06

dsilveira


1 Answers

It might be a little late but still. There is no need for a plugin or library, the solution could be very trivial. Here a basic example of how you can monitor ClipBoard content:

#creating a listening Stream:
final clipboardContentStream = StreamController<String>.broadcast();

#creating a timer for updates:
Timer clipboardTriggerTime;

clipboardTriggerTime = Timer.periodic(
# you can specify any duration you want, roughly every 20 read from the system
      const Duration(seconds: 5),
      (timer) {
        Clipboard.getData('text/plain').then((clipboarContent) {
          print('Clipboard content ${clipboarContent.text}');

          # post to a Stream you're subscribed to
          clipboardContentStream.add(clipboarContent.text);
        });
      },
    );

# subscribe your view with
Stream get clipboardText => clipboardController.stream

# and don't forget to clean up on your widget
@override
void dispose() {
  clipboardContentStream.close();

  clipboardTriggerTime.cancel();
}
like image 168
Pavlik Avatar answered Nov 08 '22 15:11

Pavlik