3

I have a TextFormField where the user should enter a string in the following format:

XX-XX-XX

Is there anyway to automatically add the "-" as the user is typing?

Thanks

ehg60864
  • 31
  • 2

2 Answers2

7

This should work for you.

class _MyHomePageState extends State<MyHomePage> {
  TextEditingController _controller = new TextEditingController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // you can have different listner functions if you wish
    _controller.addListener(onChange);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text(widget.title),
      ),
      body: Container(
        child: Center(
          child: TextFormField(
            controller: _controller,
          ),
        ),
      ),
    );
  }

  String newText = '';

  void onChange(){
    String text = _controller.text;
    if(text.length < newText.length) { // handling backspace in keyboard
      newText = text;
    }else if (text.isNotEmpty && text != newText) { // handling typing new characters.
      String tempText = text.replaceAll("-", "");
      if(tempText.length % 2 == 0){
        //do your text transforming
        newText = '$text-';
        _controller.text = newText;
        _controller.selection = new TextSelection(
            baseOffset: newText.length,
            extentOffset: newText.length
        );
      }
    }
  }
}

enter image description here

Kalpesh Kundanani
  • 5,413
  • 4
  • 22
  • 32
1

we can use MaskedTextController form extended_masked_text 2.3.1 then the condition is achievable MaskedTextController numberController = MaskedTextController(mask: '0000-0000-0000-000'); //masking type here

logi-kal
  • 7,107
  • 6
  • 31
  • 43