How to Copy or Paste Text from Clipboard with Dart in Flutter

In this example, we are going to show you the way to copy text to the clipboard or get the text from clipboard with Dart in Flutter App. The copy and paste feature is a very common feature used in mobile apps. See the example below for more details.

Copy Text to Clipboard with Dart:

import 'package:flutter/services.dart';
Clipboard.setData(ClipboardData(text: "Text here to copy"));

Paste or Get Text from Clipboard with Dart:

ClipboardData cdata = await Clipboard.getData(Clipboard.kTextPlain);
String copiedtext = cdata.text;
print(copiedtext);

OR

Clipboard.getData(Clipboard.kTextPlain).then((value){ 
    print(value.text); //value is clipbarod data
});

Full Code Example:

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

void main(){
  runApp(MyApp());
}

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Home(),
    );
  }
}

class Home extends StatelessWidget{

  TextEditingController mytext = TextEditingController();

  @override
  Widget build(BuildContext context) {
    return  Scaffold(
          appBar: AppBar( 
             title: Text("Copy & Paste with Dart"),
             backgroundColor: Colors.indigoAccent,
          ),
          body: Container(
            alignment: Alignment.center,
            padding: EdgeInsets.all(20),
            child: Column(children: [
                
                TextField(
                   controller: mytext,
                ),

                Row(
                  children:[
                    ElevatedButton(
                      onPressed: (){ 
                        Clipboard.setData(ClipboardData(text: mytext.text));
                      }, 
                      child: Text("Copy Text")
                    ),

                    Padding( 
                      padding: EdgeInsets.only(left:20),
                      child:ElevatedButton(
                        onPressed: () async {
                          Clipboard.getData(Clipboard.kTextPlain).then((value){ 
                              mytext.text = mytext.text + value.text;
                          });
                        }, 
                        child: Text("Paste Text")
                      ),
                    )
                  ]
                ),
            ],)
            
          )
       );
  }
}

Output Screenshot:

In this way, you can copy and paste text from Clipboard with Dart in Flutter apps.

No any Comments on this Article


Please Wait...