Usare la clipboard in Flutter
In questo articolo vediamo come usare la clipboard in Flutter usando il package clipboard!
E' compatibile con tutte le piattaforme; io l'ho testato in Linux e Android.
Per installarlo:
flutter pub add clipboard
Metteremo due tasti:
- il primo copia un testo che abbiamo cablato nel codice; come esercizio potreste prenderlo da una input
- il secondo incolla il valore in un'altra variabile e imposta lo state; alla fine lo visualiziamo
import 'package:flutter/material.dart';
import 'package:clipboard/clipboard.dart';
void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
useMaterial3: true,
),
home: const MyHomePage(title: 'Flutter Demo'),
);
}
}
class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});
final String title;
@override
State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
final parolaDaCopiare = "CIAO MONDO!";
String parolaCopiata = "";
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Theme.of(context).colorScheme.inversePrimary,
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
InkWell(
onTap: () {
FlutterClipboard.copy(parolaDaCopiare)
.then((value) => print('copied'));
},
child: Container(
width: 100,
height: 50,
decoration: BoxDecoration(
color: Colors.amber,
borderRadius: BorderRadius.circular(15),
),
child: const Center(
child: Text('COPIA'),
),
),
),
const SizedBox(
height: 20,
),
InkWell(
onTap: () {
FlutterClipboard.paste().then((value) {
setState(() {
parolaCopiata = value;
});
});
},
child: Container(
width: 100,
height: 50,
decoration: BoxDecoration(
color: Colors.green,
borderRadius: BorderRadius.circular(15),
),
child: const Center(
child: Text('INCOLLA'),
),
),
),
const SizedBox(
height: 20,
),
Text(
'Testo incollato: $parolaCopiata',
style: const TextStyle(fontSize: 20),
),
],
),
),
);
}
}
Enjoy!
dart flutter clipboard
Commentami!