Flutter, how to copy text after pressing the button?

4,407

Solution 1

First, assign a name to your String:

String quote = "This is a very awesome quote";

Second, copy the String to the clipboard 😊:

onPressed: (){
    Clipboard.setData(ClipboardData(text: quote));
},

To notify the user that it's done you could use a SnackBar:

onPressed: () =>
  Clipboard.setData(ClipboardData(text: inviteLink))
    .then((value) { //only if ->
       ScaffoldMessenger.of(context).showSnackBar(snackBar)); // -> show a notification
},

Solution 2

You can use this library clipboard_manager to do the actual act of storing the text in the clipboard. Then just access the text you want to copy through the TextEditingController instance.

RaisedButton(
  child: Text('Copy'),
  onPressed: () {
    ClipboardManager.copyToClipBoard(
            _textEditingController.value.text)
        .then((result) {
      final snackBar = SnackBar(
        content: Text('Copied to Clipboard'),
        action: SnackBarAction(
          label: 'Undo',
          onPressed: () {},
        ),
      );
      Scaffold.of(context).showSnackBar(snackBar);
    });
  },
),

or access the String through a variable

RaisedButton(
  child: Text('Copy'),
  onPressed: () {
    ClipboardManager.copyToClipBoard(
            _variableContainingString)
        .then((result) {
      final snackBar = SnackBar(
        content: Text('Copied to Clipboard'),
        action: SnackBarAction(
          label: 'Undo',
          onPressed: () {},
        ),
      );
      Scaffold.of(context).showSnackBar(snackBar);
    });
  },
),

Solution 3

you can use this plugin clipboard

FlutterClipboard.copy('hello flutter friends').then(( value ) => print('copied'));
Share:
4,407
Jakub Padło
Author by

Jakub Padło

Updated on December 16, 2022

Comments

  • Jakub Padło
    Jakub Padło over 1 year

    For beginning i am really sorry for my not perfect English ;)

    I want to create a button that will copy the text value when this button is pressed. I was looking for it but I found no information. How can I create automatic copying in flutter framework?

    Thank you in advance for your help.

  • Alann Maulana
    Alann Maulana over 3 years
    no need 3rd party lib, just import import 'package:flutter/services.dart'; and use Clipboard