Jakub Padło
Jakub Padło

Reputation: 733

Flutter, how to copy text after pressing the button?

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.

Upvotes: 13

Views: 17606

Answers (2)

Nuqo
Nuqo

Reputation: 4091

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
},

Upvotes: 38

Oliver Atienza
Oliver Atienza

Reputation: 661

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);
    });
  },
),

Upvotes: 2

Related Questions