onTextSelectionChanged property

PdfTextSelectionChangedCallback? onTextSelectionChanged
final

Called when the text is selected or deselected in SfPdfViewer.

The globalSelectedRegion and selectedText values in the PdfTextSelectionChangedDetails will be updated when the text is selected or deselected.

See also: PdfTextSelectionChangedDetails.

This example demonstrates how to show the context menu after the text selection using the onTextSelectionChanged callback.

class _MyHomePageState extends State<MyHomePage> {
 OverlayEntry? _overlayEntry;
 final GlobalKey<SfPdfViewerState> _pdfViewerKey = GlobalKey();
 final PdfViewerController _pdfViewerController = PdfViewerController();
 void _showContextMenu(BuildContext context, PdfTextSelectionChangedDetails details) {
 final OverlayState _overlayState = Overlay.of(context)!;
 _overlayEntry = OverlayEntry(
 builder: (context) => Positioned(
 top: details.globalSelectedRegion!.center.dy - 55,
 left: details.globalSelectedRegion!.bottomLeft.dx,
 child: RaisedButton(
 onPressed: () {
 Clipboard.setData(ClipboardData(text: details.selectedText));
 _pdfViewerController.clearSelection();
 },
 color: Colors.white,
 elevation: 10,
 child: Text('Copy', style: TextStyle(fontSize: 17)),
 ),
 ),
 );
 _overlayState.insert(_overlayEntry!);
 }

 @override
 Widget build(BuildContext context) {
   return Scaffold(
     appBar: AppBar(
       title: Text(widget.title),
     ),
     body: SfPdfViewer.asset(
       'assets/sample.pdf',
       enableTextSelection: true,
       onTextSelectionChanged:
           (PdfTextSelectionChangedDetails details) {
         if (details.selectedText == null && _overlayEntry != null) {
           _overlayEntry!.remove();
           _overlayEntry = null;
         } else if (details.selectedText != null &&
         _overlayEntry == null) {
           _showContextMenu(context, details);
         }
       },
       key: _pdfViewerKey,
       controller: _pdfViewerController,
     ),
   );
 }
}

Implementation

final PdfTextSelectionChangedCallback? onTextSelectionChanged;