Search code examples
androidflutterflutter-layouttextinputflutter-text

Add a prefix to every line in a multiline Text Input in Flutter?


I wanted to know if there was a way of adding a prefix (like "- ") to every line in a multiline Text Input in Flutter.

For example:

Hello

World!

Would become:

-Hello

-World!

This is my code:

TextField(
  maxLines: null,
  controller: _elementsController,
  textCapitalization: TextCapitalization.sentences,
  style: TextStyle(
    fontSize: 18.0,
  ),
  decoration: InputDecoration(
    contentPadding: EdgeInsets.all(0.0),
    labelText: 'Elements',
  ),
),

Solution

  • U can add a - everytime a new line is created.

    Add this in your initState(),

    final prefix = '-';
    _elementsContoller.addListener(() {
      if(_elementsController.text.endsWith('\n')) {
        // Add the prefix everytime a new line is created
        _elementsController.text +=  prefix;
      }
    }
    

    If these changes should be made after the input,

    text.replaceAll('\n', '\n$prefix');