Home > Blockchain >  Dart: Copy text to clipboard with one-click
Dart: Copy text to clipboard with one-click

Time:10-09

I want the email to be copied to the clipboard with one click. Because I want to make a new feature in my app. But the variables must exist!

import 'package:flutter/material.dart';
import 'package:mcgapp/widgets/app_bar.dart';
import 'package:flutter/services.dart';

import '../classes/teacher.dart';

class TeacherDetailsScreen extends StatelessWidget {
  const TeacherDetailsScreen({
    Key? key,
    required this.teacher,
  }) : super(key: key);

  final Teacher teacher;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: "${teacher.pronoun} ${teacher.name}",
      ),
      body: ListView(
        children: [
          ListTile(
            title: Text("${teacher.firstname} ${teacher.name}" != ""
                ? "${teacher.firstname} ${teacher.name}"
                : "No Name"),
            leading: const Icon(Icons.person),
          ),
          ListTile(
            title: Text(teacher.subject != ""
                ? teacher.subject
                : "No Subjects"),
            leading: const Icon(Icons.subject),
          ),
          ListTile(
            title: Text(teacher.kuerzel != ""
                ? teacher.kuerzel
                : "Nothing"),
            leading: const Icon(Icons.tag),
          ),
          ListTile(
            title: Text(teacher.email != ""
                ? teacher.email
                : "No Mail"),
            leading: const Icon(Icons.email),
          )
        ],
      ),
    );
  }
}

This ListTitel is meant by "email" :

 ListTile(
            title: Text(teacher.email != ""
                ? teacher.email
                : "No Mail"),
            leading: const Icon(Icons.email),

CodePudding user response:

You can copy the String to the clipboard like this in an example:

void copyToClipboard(String email) {
Clipboard.setData(ClipboardData(text: email));
}

Moreover, you can notify the user with a snackbar or flushbar on your UI screen.

void copyToClipboard(String email) {
    Clipboard.setData(ClipboardData(text: email)).then((value) { //only if ->
       ScaffoldMessenger.of(context).showSnackBar(snackBar)); // -> notify the user
}

CodePudding user response:

You can use the Clipboard class from flutter/services.dart and use the setData method on click.

CodePudding user response:

You can do this with a services lib provided by flutter first, import it

import 'package:flutter/services.dart';

Set the clipboard with your email text or any string value you can call this method on the list onTap() function

await Clipboard.setData(ClipboardData(text: /* your data here */));

Note: Please use async while calling this Clipboard because it is asynchronous

  • Related