The SelectionText widget in Flutter is a versatile tool that enables users to interact with selected text within a Flutter application. This widget offers developers the flexibility to enhance user experience by adding features like copying text, sharing, highlighting, or executing specific actions on selected text.
Attributes of the SelectionText widget in Flutter typically include:
onSelectionChanged: A callback function triggered when text is selected.
onCopy: A callback function triggered when the user copies the selected text.
onHighlight: A callback function triggered when the selected text is highlighted.
onShare: A callback function triggered when the user chooses to share the selected text.
customActions: A list of custom actions that can be performed on the selected text.
style: Custom styling options for the widget.
Now, let's explore an example of how to implement the SelectionText widget in a Flutter application:
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'SelectionText Widget Example',
home: SelectionTextDemo(),
);
}
}
class SelectionTextDemo extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('SelectionText Widget Example'),
),
body: Center(
child: SelectionTextWidget(),
),
);
}
}
class SelectionTextWidget extends StatefulWidget {
@override
_SelectionTextWidgetState createState() => _SelectionTextWidgetState();
}
class _SelectionTextWidgetState extends State<SelectionTextWidget> {
String selectedText = '';
@override
Widget build(BuildContext context) {
return GestureDetector(
onLongPress: () {
setState(() {
selectedText = 'Text selected: ${Clipboard.getData('text/plain').toString()}';
});
},
child: Container(
padding: EdgeInsets.all(16.0),
child: Text(
'Lorem ipsum dolor sit amet, consectetur adipiscing elit. Integer nec odio. Praesent libero.',
style: TextStyle(fontSize: 18.0),
),
),
);
}
}
In this example, we've created a simple Flutter application with a SelectionTextWidget class. This widget displays a text paragraph and allows users to select text by long-pressing on it. When the text is selected, the onLongPress callback is triggered, updating the selectedText variable with the selected text. The selected text is then displayed below the paragraph using a Text widget.
This is a basic example of how the SelectionText widget can be implemented in a Flutter application. Developers can further customize its functionality and appearance based on the specific requirements of their app.