dart - 在TextFormField中插入Dash

标签 dart flutter

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

XX-XX-XX

无论如何,用户键入时是否会自动添加“-”?

谢谢

最佳答案

这应该为您工作。

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

关于dart - 在TextFormField中插入Dash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55664695/

相关文章:

dart - 如何订阅可观察领域的变更

ios - 发送Http.MultipartRequest作为 flutter 数组?

flutter - Flutter:无法显示AlertDialog

flutter - 如何在 flutter 中获取屏幕高度

flutter - 为单个容器设置两种不同的颜色

arrays - 根据构造函数参数对 Dart 列表进行排序

flutter - 如何使用 Flutter 小部件测试器找到 'selected' ListTile?

flutter - 我需要在 url 启动器 TEL 中登录标签,但它会自动删除

flutter - 如何在 flutter 中使用反射访问下划线属性?

带有音频播放器的 Flutter Bloc