在TextFormField中插入Dash

问题描述 投票:0回答:1

我有一个TextFormField,用户应该按以下格式输入一个字符串:

XX-XX-XX

无论如何在用户输入时自动添加“ - ”?

谢谢

dart flutter
1个回答
0
投票

这应该适合你。

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

© www.soinside.com 2019 - 2024. All rights reserved.