Flutter custom selection toolbar
A while back I needed to implement a custom option for text selection toolbar. What is a text selection toolbar you might ask? It is the options- box that is shown when highlighting text:
What I needed was a custom button that could execute a custom action on the selected text.
To get this selection behavior for text in Flutter a
SelectableText widget must be used. By default there are some default options that can be enabled.
However, in order to get something truly customizable we need to extend the existing
In essence we need to extend one of the existing
TextSelectionControls classes. For my use case I’m going to extend
MaterialTextSelectionControls class. If you are interested to learn why there is no easier way there is an open issue in GitHub.
Here is the whole class you can copy pasta this to a custom_text_selection_file.dart.
As the “custom functionality” I’m getting the start and end index of the selection. However, you can do whatever you desire with the text selection delegate.
In the UI code we can use the
Here is the code for the UI.
Now when we run the application and click the custom button we get this text as output.
If you have suggestions or questions leave them below, and give a clap if you enjoyed. Thank you for reading! :)