Skip to content
DeveloperMemos

Copy to the Clipboard with Flutter

Flutter, Flutter Tips1 min read

I'll start off by saying this is going to be a pretty short post. Copying to the system clipboard with Flutter is really easy and it doesn't require any third party packages. Let's get straight into it.

Imports

Like I said you don't need to add any third party packages but you do need to import one of the standard libraries(services):

1import 'package:flutter/services.dart';

Copy text to the clipboard

After that you just need to use the setData method from Clipboard, but first you have to create some ClipboardData to feed to it. All together it's two lines of code:

1final data = ClipboardData(text: "Some text!");
2Clipboard.setData(data);

By the way, you can also await the setData method, so if you needed to show a dialog or something like that afterwards you can:

1final data = ClipboardData(text: "Some text!");
2await Clipboard.setData(data);
3ScaffoldMessenger.of(context).showSnackBar(
4 SnackBar(
5 content: const Text('Copied to clipboard!'),
6 ),
7);

Reading the clipboard

You can also use the ClipboardData class to read from the clipboard, you just need to use getData instead of setData:

1final data = await Clipboard.getData(Clipboard.kTextPlain);
2print("Text: ${data?.text}");

That being said I couldn't get this to work correctly using DartPad or an iOS simulator so the above method could be a bit hit or miss(clipboard access is getting stricter by the year due to security issues too...).