乐闻世界logo
搜索文章和话题

Flutter ( Dart ) How to add copy to clipboard on tap to a app?

1个答案

1

In Flutter, to copy text to the clipboard upon clicking, we can utilize the Clipboard class from the services library.

  1. First, import the services library into your Flutter project:
dart
import 'package:flutter/services.dart';
  1. Next, define a function that copies text to the clipboard when triggered (e.g., by a button click):
dart
void copyToClipboard(String textToCopy) async { await Clipboard.setData(ClipboardData(text: textToCopy)); }
  1. Then, in your UI component, add a button and invoke the copyToClipboard method on its click event:
dart
ElevatedButton( onPressed: () { copyToClipboard("This is the text to copy"); }, child: Text("Copy to Clipboard"), )

Here is a complete example:

dart
import '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 回复

你的答案