In Flutter, to copy text to the clipboard upon clicking, we can utilize the Clipboard class from the services library.
- First, import the
serviceslibrary into your Flutter project:
dartimport 'package:flutter/services.dart';
- Next, define a function that copies text to the clipboard when triggered (e.g., by a button click):
dartvoid copyToClipboard(String textToCopy) async { await Clipboard.setData(ClipboardData(text: textToCopy)); }
- Then, in your UI component, add a button and invoke the
copyToClipboardmethod on its click event:
dartElevatedButton( onPressed: () { copyToClipboard("This is the text to copy"); }, child: Text("Copy to Clipboard"), )
Here is a complete example:
dartimport 'package:flutter/material.dart'; import 'package:flutter/services.dart'; void main() { runApp(MyApp()); } class MyApp extends StatelessWidget { Widget build(BuildContext context) { return MaterialApp( home: Scaffold( appBar: AppBar( title: Text('Copy to Clipboard Example'), ), body: Center( child: CopyTextButton(), ), ), ); } } class CopyTextButton extends StatelessWidget { final String textToCopy = "This is the text to copy"; void copyToClipboard() async { await Clipboard.setData(ClipboardData(text: textToCopy)); } Widget build(BuildContext context) { return ElevatedButton( onPressed: copyToClipboard, child: Text("Copy to Clipboard"), ); } }
In this example, clicking the 'Copy to Clipboard' button copies the text from textToCopy to the clipboard. Users can paste this text into any other application. This feature is commonly used in development, particularly in applications requiring convenient and quick text copying.
2024年8月8日 01:14 回复