A2oz

How Do You Copy Text From a Widget in Flutter?

Published in Flutter Development 2 mins read

You can copy text from a widget in Flutter using the Clipboard class. This class provides methods for copying and pasting text to and from the system clipboard.

Copying Text

Here's how to copy text from a widget in Flutter:

  1. Import the clipboard package:

    import 'package:flutter/services.dart';
  2. Get the text to copy:

    • You can obtain the text from a TextField, Text widget, or any other source.
    • Store the text in a variable.
  3. Use Clipboard.setData() to copy the text:

    Clipboard.setData(ClipboardData(text: 'Your text to copy'));
    • Replace 'Your text to copy' with the actual text you want to copy.

Example

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

class CopyTextExample extends StatefulWidget {
  @override
  _CopyTextExampleState createState() => _CopyTextExampleState();
}

class _CopyTextExampleState extends State<CopyTextExample> {
  String _textToCopy = 'This is the text to copy.';

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Copy Text Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(_textToCopy),
            ElevatedButton(
              onPressed: () {
                Clipboard.setData(ClipboardData(text: _textToCopy));
                // Display a message or snackbar to confirm copying.
              },
              child: Text('Copy Text'),
            ),
          ],
        ),
      ),
    );
  }
}

Explanation:

  • The code imports the clipboard package to access clipboard functionality.
  • A TextField is used to display the text to copy.
  • An ElevatedButton triggers the copying action when pressed.
  • The Clipboard.setData() method copies the text to the system clipboard.

Additional Notes:

  • You can use Clipboard.getData() to retrieve text from the clipboard.
  • You can also copy other data types like images using the ClipboardData class.

Related Articles