Tech Trends, Technology Articles

How to Make a Multicolored TextField in Flutter

Changing the Text Field Background Color in Flutter

Earlier this month, Akvelon’s team announced that we launched our Flutter Code Editor – an open-source and feature-rich code editor widget for Flutter applications with syntax highlighting that is already being used by developers to make code editing easier. However, the out-of-the-box standard TextField widget only works with a single color. In this article, we will explain a simple way to upgrade that and make Flutter change the text field background colors.

The TextField widget itself does not impose any styling. Instead, it asks its TextEditingController to produce a styled TextSpan object, which is a piece of text with a style.

Creating TextSpan – Text Field Background Color in Flutter

See the full runnable example here.

The TextField passes its style to its TextEditingController and the default implementation just puts it into the TextSpan object, which is how the color is normally applied.

To override this, subclass the TextEditingController and override the method:

Gradient Demo Gif - Text Field Background Color Flutter

See the full code here.

You can also do much more complex processing. For instance, we made code highlighting by parsing the syntax tree and colorizing keywords, literals, comments, etc. differently:

 

Syntax Demo Gif - Text Field Background Color Flutter

We start by importing the highlighting and the flutter_highlighting packages we made for another project:

Then, we parse the text and get a simple form of a syntax tree:
Next is to walk the syntax tree and return a TextSpan for each node:

See the full code here.

Essentially, the TextEditingController class is the gate to all sorts of customization. We went further down that road and made an advanced code editor that can do this:

Flutter Code Editor

 

By experimenting with multi-colored code highlighting, we've been able to expand text customization possibilities in Flutter. We've achieved this by extending the TextEditingController, enabling us to create a multi-colored TextField. A simple implementation can display a gradient effect, while a more complex use-case allows syntax highlighting in a code editor, colorizing different components of code.

Explore these features and more in our article on the blog.

AlexeyI

Alexey Inkin

Lead Flutter Developer at Akvelon