How to use SelectableText

Do you want to build a selectable text in your flutter application? Try SelectableText widget. They give better user experience to the user and make them to feel like a native application.

How to use SelectableText

Do you want to build a selectable text in your flutter application? Try SelectableText widget. They give better user experience to the user and make them to feel like a native application.

SelectableText are the single style widget which displays the text and react's to our touches.

Single style - example

SelectableText(
  'You can select me now!',
  textAlign: TextAlign.center,
  style: TextStyle(fontWeight: FontWeight.bold),
)

Multiple style can be applied using the SelectableText.rich() method.

Multiple style - example

const SelectableText.rich(
  TextSpan(
    text: 'Hi There - mobilelabs', // default text style
    children: <TextSpan>[
      TextSpan(text: ' Wonderful ', style: TextStyle(fontStyle: FontStyle.italic)),
      TextSpan(text: 'Life', style: TextStyle(fontWeight: FontWeight.bold)),
    ],
  ),
)

How do we control the cursor?

By default cursor are disable in the SelectableText widget, we can enable it by setting the showCursor to true.

SelectableText(
  'Hello! How are you?',
  textAlign: TextAlign.center,
  style: TextStyle(fontWeight: FontWeight.bold),
  showCursor: true
)

Can we control the toolbar options?

Yes, using ToolbarOptions we can enable/disable the copy, cut, paste and selectAll menus when we select the text.

SelectableText(
  'You can only copy me!',
  textAlign: TextAlign.center,
  style: TextStyle(fontWeight: FontWeight.bold),
  toolbarOptions(copy: true),
)

Reference

1. https://api.flutter.dev/flutter/material/SelectableText-class.html
2. https://www.youtube.com/watch?v=ZSU3ZXOs6hc