Flutter custom selection toolbar

Kristian Tuusjarvi
3 min readMay 19, 2021

--

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:

Text selection toolbar by default.

What I needed was a custom button that could execute a custom action on the selected text.

Custom toolbar with a custom button.

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.

Default ToolbarOptions.

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.

Extending MaterialTextSelectionControls class.

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.

Custom functionality of the custom button.

In the UI code we can use the CustomTextSelectionControlsin a SelectableTextwidget.

Code for the UI.

Here is the code for the UI.

UI code using CustomTextSelectionControls.

Result

Now when we run the application and click the custom button we get this text as output.

Example of the application.

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! :)

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

--

--

Kristian Tuusjarvi
Kristian Tuusjarvi

No responses yet

Write a response