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:
-
Import the
clipboard
package:import 'package:flutter/services.dart';
-
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.
- You can obtain the text from a
-
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.
- Replace
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.