Making a markdown text editor in Flutter
September 07, 2020
I’m currently working on an app called Goryon - A twtxt mobile app. One of the few features of the app is it enables you to compose twts (kinda like your twitter message but it allows you to use Markdown).
Final Product
Let’s get started
To do that you’ll need a TextEditingController
that is connected to a TextField
_textController = TextEditingController()
....
TextFormField(
autofocus: true,
maxLines: 8,
controller: _textController
)
Then I created a function that surrounds the highlighted text in the text box with a markdown syntax
void _surroundTextSelection(String left, String right) {
final currentTextValue = _textController.value.text;
final selection = _textController.selection;
final middle = selection.textInside(currentTextValue);
final newTextValue = selection.textBefore(currentTextValue) +
'$left$middle$right' +
selection.textAfter(currentTextValue);
_textController.value = _textController.value.copyWith(
text: newTextValue,
selection: TextSelection.collapsed(
offset: selection.baseOffset + left.length + middle.length,
),
);
}
left is the string on the left hand side. right is the string on the right hand side.
This is how bolding a text would look like:
_surroundTextSelection('**', '**')
Adding a code block
_surroundTextSelection('```', '```')
Adding an Image
_surroundTextSelection(''),
You get the point.
Check out the full code in this repo. That’s all for now!