Skip to content

Instantly share code, notes, and snippets.

@anirudhb
Last active April 20, 2020 18:29
Show Gist options
  • Save anirudhb/84e8fa9020e5d65e4fd0222e2ad90c14 to your computer and use it in GitHub Desktop.
Save anirudhb/84e8fa9020e5d65e4fd0222e2ad90c14 to your computer and use it in GitHub Desktop.
Copyable text on web (hover for copy button + tooltip)

Copyable text widget on web

Shows a copy button when hovered, then shows a tooltip after copied.

DartPad

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding:
const EdgeInsets.symmetric(vertical: 8, horizontal: 0),
child: HoverCopy("Hello")),
Padding(
padding:
const EdgeInsets.symmetric(vertical: 8, horizontal: 0),
child: HoverCopy("Hii!!!")),
Padding(
padding:
const EdgeInsets.symmetric(vertical: 8, horizontal: 0),
child: HoverCopy("Stay safe, baby!")),
],
),
),
),
);
}
}
class HoverCopy extends StatefulWidget {
final String text;
const HoverCopy(this.text);
@override
_HoverCopyState createState() => _HoverCopyState();
}
class _HoverCopyState extends State<HoverCopy> {
bool _isHovering = false;
bool _showingTooltip = false;
void _onHover(PointerEvent ev) {
setState(() {
_isHovering = true;
});
}
void _onExit(PointerEvent ev) {
setState(() {
_isHovering = false;
_showingTooltip = false;
});
}
void _copyText() {
Clipboard.setData(ClipboardData(text: widget.text));
setState(() {
_showingTooltip = true;
});
}
@override
Widget build(BuildContext context) {
Widget icon = Icon(
Icons.content_copy,
size: Theme.of(context).textTheme.bodyText1.fontSize,
);
// Theme.of(context).textTheme.bodyText1.fontSize
return MouseRegion(
onHover: _onHover,
onExit: _onExit,
child: Row(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
Text(widget.text),
if (_isHovering)
Container(
margin: const EdgeInsets.only(left: 7),
child: InkWell(
onTap: _copyText,
child: _showingTooltip
? Tooltip(child: icon, message: "Copied!")
: icon,
hoverColor:
Theme.of(context).textTheme.bodyText1.color.withAlpha(31),
splashColor:
Theme.of(context).textTheme.bodyText1.color.withAlpha(128),
radius: Theme.of(context).textTheme.bodyText1.fontSize,
),
),
],
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment