DEV Community

Daven
Daven

Posted on

Building a simple markdown editor with Flutter

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).

What we're building

What we're building

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
                        )
Enter fullscreen mode Exit fullscreen mode

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,
      ),
    );
  }
Enter fullscreen mode Exit fullscreen mode

left is the string on the left hand side. right is the string on the right hand side.

To make the text bold, you can do:

_surroundTextSelection('**', '**')
Enter fullscreen mode Exit fullscreen mode

Adding a code block

_surroundTextSelection('```

', '

```')
Enter fullscreen mode Exit fullscreen mode

Adding an Image

_surroundTextSelection('![](https://', ')'),
Enter fullscreen mode Exit fullscreen mode

Check out the full code in this repo. That's all for now!

Top comments (0)