在TextFormField中插入Dash [英] Insert Dash in TextFormField

查看:72
本文介绍了在TextFormField中插入Dash的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个TextFormField,用户应在其中输入以下格式的字符串:

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?

谢谢

推荐答案

这应该对您有用。

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
        );
      }
    }
  }
}

< a href = https://i.stack.imgur.com/tjWTq.gif rel = nofollow noreferrer>

这篇关于在TextFormField中插入Dash的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆