How to insert/show HTML element in a TextFormField in Flutter?

Viewed 149

I have a feature I'm trying to develop in a flutter that allows users to @ someone in a note they are leaving, just like many messaging apps like Slack, etc. In this scenario, they would be able to type in the TextFormField, and then from a separate UI element, select a user to include.

In the TextFormField, it would appear something like this:

enter image description here

I don't currently see a way how I could implement this? TextField and TextFormField seem to only support Strings. Again, the use-case would be where from a list of people, they could select one/more..and wherever the cursor is in the text form field, it would insert the HTML element/or whatever element that could display background color, etc.

Any ideas?

Note that I've researched a number of html editors, such as html_editor_enhanced, but they seem very clunky/overkill for something this simple.


2 Answers

After further research, I found the following article, which walks through a nice clean solution on how to do this:

https://www.flutterclutter.dev/flutter/tutorials/styling-parts-of-a-textfield/2021/101326/

You can basically use the example he provided, but then you just need to change the regular expression to look for any words starting with @ symbol per below. Note that I kept the first expression which changes the color of the punctuation, but the cool thing is, you can define any number of styles and regular expressions to change format dynamically.

final TextEditingController textEditingController =
        StyleableTextFieldController(
      styles: TextPartStyleDefinitions(
        definitionList: <TextPartStyleDefinition>[
          TextPartStyleDefinition(
            style: const TextStyle(
              color: Colors.green,
              fontWeight: FontWeight.bold,
            ),
            pattern: '[\.,\?\!]',
          ),
          TextPartStyleDefinition(
            style: const TextStyle(
              color: Color.fromRGBO(65, 131, 196, 1),
              backgroundColor: Color.fromRGBO(232, 245, 250, 1),
              fontWeight: FontWeight.bold,
            ),
            pattern: r'\@(\w+)'
          ),
        ],
      ),
    );

Take a look at this package called extended_text_field, seems to do what you want to achieve.

If you don't want to use a package, you can read its source code and extract the relevant parts.

Related