Flutter custom selection toolbar
Introduction
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.

SelectableText
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 existingMaterialTextSelectionControls.
CustomTextSelectionControls
In essence we need to extend one of the existing TextSelectionControls
classes. For my use case I’m going to extendMaterialTextSelectionControls
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 CustomTextSelectionControls
in a SelectableText
widget.

Here is the code for the UI.
Result
Now when we run the application and click the custom button we get this text as output.

This article was inspired by this GitHub thread. For more information about custom text selection toolbars check out this example by justimc.
If you have suggestions or questions leave them below, and give a clap if you enjoyed. Thank you for reading! :)