Scrolling through your favorite media platform, you see a nice tweet, post, or message. Click a button, the content is copied, you’re off to WhatsApp, click paste, and off it goes. Easy, yeah?
Exactly — that’s how easy our life is through the clipboard. Imagine if you had to type, word for word, every quote, tweet, or message you saw online. Terrible! Now you see the importance of the clipboard and the ease it brings to us.
In this article, we will be looking at how to implement the copy to clipboard feature in a sample application. Using a step-by-step walkthrough, we will look at implementing this feature with and without external dependencies.
Let’s start off by diving into what a clipboard is. The clipboard is a location that holds pieces of data temporarily, from which it can then be pasted in a new location on the device. In our context, the clipboard holds the text we would want to copy until we paste it in a new location. Considering the amount of text we would have to manually copy and paste without the clipboard feature, we can collectively agree the clipboard is a super important aspect of our lives.
The Flutter framework gives us the ability to access and control the clipboard, writing to it when we copy text and reading from it when we paste. Depending on your use case, you can implement copy to clipboard in Flutter either with or without dependencies.
Aside from the implementations Flutter grants us access to, there are packages available that make implementing the copy to clipboard feature way easier. One of these packages is clipboard
. With this package, we have access to methods through which we can manipulate the clipboard, copying/writing to it when we want and reading/pasting from it to a new location of our choice.
The copy to clipboard feature can be implemented using the Clipboard
class that Flutter grants access to. The Clipboard
class exposes two methods: setData
and getData
.
setData
The setData
method is used to add/copy data to the keyboard. All you have to do is call the method on the Clipboard
class and then pass in your text using the ClipboardData
object. Here is an example of how it is used:
Clipboard.setData(ClipboardData(text: "your text"))
getData
The getData
method is used to read/paste the data from the clipboard in a new location. We would have to pass in the format for which the pasted item will be. In our case, the item would be text, so the format will be Clipboard.kTextPlain
. Here is an example of how it is used:
ClipboardData cdata = await Clipboard.getData(Clipboard.kTextPlain); String copiedtext = cdata.text;
With these two methods, you can easily work with the clipboard in your Flutter application, improving the overall user experience. We’ll have a walkthrough of both implementations in our sample application. We’ll create a sample application where we can input text, copy it, and then paste into a new location.
Time to get our hands dirty. In this section, we’ll look at implementing the copy to clipboard feature in a sample app. We’ll be able to enter a custom text and then, with the click of a button, it gets written to the clipboard. We can then paste to another location when we click another button. We’ll implement the feature both with and without dependencies. Let’s get to it then! Start off by creating a new project using the command below:
flutter create copy_to_clipboard
This will generate all the base files needed for the app to run. In the application we have two pages: one showing the implementation without dependencies and the other page showing the implementation with dependencies. Create two new files in your lib
folder, home_view.dart
and second_view.dart
.
In home_view.dart
, create a stateless widget named HomeView
. It will hold the implementation with external dependencies.
class HomeView extends StatelessWidget { const HomeView({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Diary App'), ), body: Column( children: [], ), ); } }
In the second file, second_view.dart
, create a stateless widget and name it SecondView
(for lack of a better name at the moment). This will hold the implementations without dependencies.
class SecondView extends StatelessWidget { const SecondView({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: const Text('Second View'), ), body: Column( children: [], ), ); } }
We will be using the Clipboard
package for this implementation. Head over to pub.dev and add the package as a dependency in your app. To do that, go to your pubspec.yaml
file and add the clipboard
package as a dependency in the dependencies
section.
name: copy_to_clipboard description: A new Flutter project. publish_to: 'none' version: 1.0.0+1 environment: sdk: ">=2.15.1 <3.0.0" dependencies: flutter: sdk: flutter cupertino_icons: ^1.0.2 clipboard: ^0.1.3 dev_dependencies: flutter_test: sdk: flutter flutter_lints: ^1.0.0 flutter: uses-material-design: true
After that, run the command below to fetch the package to be used locally.
flutter pub get
Next, go to the new file we created earlier home_view.dart
. This is where we will implement the copy
and paste
functionalities.
First, add two TextEditingControllers
, which control the two TextFields
we will use.
Let’s use the behavior of a chat message as an example. You can copy the message, move to another TextField
box, and paste. The first controller gets the text and when you paste, the first controller updates the second controller or any other text on the screen you want it to.
TextEditingController diaryControllerWithPackageOne = TextEditingController(); TextEditingController diaryControllerWithPackageTwo = TextEditingController();
Moving to the interesting part, let’s implement the Copy
functionality. Add a TextField
and TextButton
, and assign the diaryControllerWithPackageOne
controller to the TextField
.
In the onPressed
parameter of the TextButton
, call the copy
method from the FlutterClipboard
class provided by the package. We also add a SnackBar
to inform the user that the text has been copied.
After this, pass in the text from diaryControllerWithPackageOne.text
to it.
TextField( controller: diaryControllerWithPackageOne, decoration: const InputDecoration( labelText: 'Enter diary input for today', border: OutlineInputBorder(), ), ), TextButton( onPressed: () async { FlutterClipboard.copy(diaryControllerWithPackageOne.text) .then( (value) { return ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('Text Copied'), ), ); }, ); }, style: ButtonStyle( backgroundColor: MaterialStateProperty.all<Color>(Colors.blue), ), child: const Text( 'Copy', style: TextStyle(color: Colors.white), ), ),
With this, the copy
functionality has been successfully implemented! Let’s implement the paste
functionality. Add a TextField
and TextButton
. Assign the diaryControllerWithPackageTwo
to the TextField
.
In the onPressed
parameter of the TextButton
, call the paste
method from the FlutterClipboard
class in the clipboard
package.
Assign the result to diaryControllerWithPackageTwo.text
, thereby displaying the copied text in the TextField
.
TextField( controller: diaryControllerWithPackageTwo, decoration: const InputDecoration( labelText: 'Pasted text will appear here', border: OutlineInputBorder(), ), ), TextButton( onPressed: () async { FlutterClipboard.paste().then( (value) => diaryControllerWithPackageTwo.text = value, ); }, style: ButtonStyle( backgroundColor: MaterialStateProperty.all<Color>(Colors.blue), ), child: const Text( 'Paste', style: TextStyle(color: Colors.white), ), ),
Lastly, let’s add a button to navigate to the next page, which will hold the implementation without dependencies.
ElevatedButton( onPressed: () { Navigator.push( context, MaterialPageRoute( builder: (context) => const HomeView(), ), ); }, child: const Text('Go To Second View'), ),
With this, we’ve successfully implemented both copy
and paste
using the FlutterClipboard
class that comes with the external dependency/package. Let’s move on to implementing without dependencies.
In the SecondView
widget in second_view.dart
, add two TextEditingControllers
: one to control the TextField
and the other to receive the text we want to paste.
TextEditingController diaryTextEditingController = TextEditingController(); TextEditingController diaryTwoTextEditingController = TextEditingController();
Next, add a TextField
and assign the first TextEditingController
, diaryTextEditingController
, to it. Add a TextButton
, which we will use to trigger the Copy
functionality.
We’ll use the setData
method from Flutter’s Clipboard
class to copy/write the text we want to the clipboard, ready to be pasted in a new location. As a plus, we’ll add a SnackBar
to inform the user that the text has been copied.
Since the text is coming in from what was passed into the first TextField
, we pass the diaryTextEditingController.text
value to the text parameter of the setData
method.
TextField( controller: diaryTextEditingController, decoration: const InputDecoration( labelText: 'Enter diary input for today', border: OutlineInputBorder(), ), ), TextButton( onPressed: () async { Clipboard.setData( ClipboardData(text: diaryTextEditingController.text)) .then( (value) { return ScaffoldMessenger.of(context).showSnackBar( const SnackBar( content: Text('Text Copied'), ), ); }, ); }, style: ButtonStyle( backgroundColor: MaterialStateProperty.all<Color>(Colors.blue), ), child: const Text( 'Copy', style: TextStyle(color: Colors.white), ), ),
With this done, we can move on to the Paste
functionality. Similar to the Copy
functionality, add a TextField
and a TextButton
. Assign the second controller, diaryTwoTextEditingController
, to the TextField
.
In the onPressed
parameter of the TextButton
, call the getData
method from the Clipboard
class. We need to pass in the format, so in our case, use text/plain
— the format when retrieving texts from the clipboard.
TextField( controller: diaryTwoTextEditingController, decoration: const InputDecoration( labelText: 'Pasted text will appear here', border: OutlineInputBorder(), ), ), TextButton( onPressed: () async { Clipboard.getData('text/plain').then((value) { diaryTwoTextEditingController.text = value!.text!; }); }, style: ButtonStyle( backgroundColor: MaterialStateProperty.all<Color>(Colors.blue), ), child: const Text( 'Paste', style: TextStyle(color: Colors.white), ), ),
Lastly, let’s add a button to navigate back to the previous page:
ElevatedButton( onPressed: () { Navigator.pop(context); }, child: const Text('Back'), ),
With this done, we’re set up and can go ahead to copy and paste from/to our clipboard in our Flutter app using only the Clipboard
class.
We can now go ahead and run our application. Run the command below to run the sample application:
flutter pub run
Copy To Clipboard Flutter
Uploaded by Adegoke David on 2022-03-26.
Hurray! We’ve come a long way, and you’ve seen the various ways of implementing the copy to clipboard feature in a Flutter application. With this, you’ve successfully learned a way of easing the user experience in your application (and saving your user a whole lot of stress, you might agree).
Check out the complete source code for the sample app. If you have any questions or inquiries, feel free to reach out to me on Twitter or LinkedIn.
Install LogRocket via npm or script tag. LogRocket.init()
must be called client-side, not
server-side
$ npm i --save logrocket // Code: import LogRocket from 'logrocket'; LogRocket.init('app/id');
// Add to your HTML: <script src="https://cdn.lr-ingest.com/LogRocket.min.js"></script> <script>window.LogRocket && window.LogRocket.init('app/id');</script>
Would you be interested in joining LogRocket's developer community?
Join LogRocket’s Content Advisory Board. You’ll help inform the type of content we create and get access to exclusive meetups, social accreditation, and swag.
Sign up nowCompare Prisma and Drizzle ORMs to learn their differences, strengths, and weaknesses for data access and migrations.
It’s easy for devs to default to JavaScript to fix every problem. Let’s use the RoLP to find simpler alternatives with HTML and CSS.
Learn how to manage memory leaks in Rust, avoid unsafe behavior, and use tools like weak references to ensure efficient programs.
Bypass anti-bot measures in Node.js with curl-impersonate. Learn how it mimics browsers to overcome bot detection for web scraping.
One Reply to "Implementing copy to clipboard in Flutter"
Thanks. found this at the right time. been thinking of how to implement this. Great read and well detailed.