1

I have a text field which I need to style for example with bold or italics parts. I tried overridding the TextEditingController's buildTextSpan and formatting the text using annotation ranges with custom styles but the edge cases were too much and I really couldn't get it to work.

So, thought about using a formatter where before every change in format I'll add a custom character, like this:

This text is |bBOLD and this is |iITALICS. Would get me this:

This text is BOLD and this is ITALICS. So I override the buildTextSpan to build the TextSpan from a parse function where I split the text by the special characters and check the initial letter of each text for formatting info.

This works well except for the fact that when I press the right arrow to go the next character after the "This text is ", the cursor will stay fixed as it thinks there are two characters but being only for formatting, they aren't there on the render.

Is there any way I could tell the textfield to ignore certain characters when selecting, moving selection or typing?

Fabrizio
  • 1,138
  • 4
  • 18
  • 41

1 Answers1

1

I think this would work!

static const kCharToBEIgnored = 0x2C;
// Here 0x2C means ',' comma
// For complete list visit https://api.flutter.dev/flutter/charcode/charcode-library.html
String get text {
  return String.fromCharCodes(
    _value.text.codeUnits.where((ch) => ch != kCharToBEIgnored),
  );
}
Ravi Garg
  • 1,378
  • 12
  • 23
  • This works for the displaying side of things but when I move the cursor, the selection gets messed up, especially when trying to select the next character before the hidden one. Is there a way to fix it? – Fabrizio Aug 18 '20 at 19:25
  • If that's the case, I think you should opt for onChanged rather than using TextEditinngController itself. See this https://stackoverflow.com/questions/56904313/texteditingcontroller-vs-onchanged – Ravi Garg Aug 19 '20 at 03:28