我正在使用 Flutter 文本字段不是文本表单字段制作温度转换器应用程序我需要限制多个点和多个符号 (+ - )?

问题描述

I need to Restrict having multiple symbol and I need to have only +,-,.and number only (Flutter Text Field)

解决方法

class MyHomePage extends StatefulWidget {
  @override
  MyHomePageState createState() {
    return new MyHomePageState();
  }
}

class MyHomePageState extends State<MyHomePage> {
  final _text = TextEditingController();
  bool _validate = false;

  @override
  void dispose() {
    _text.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('TextField Demo'),),body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,children: <Widget>[
            TextField(
              controller: _text,decoration: InputDecoration(
                labelText: 'Enter the Value',errorText: !_validate ? 'Your Message' : null,RaisedButton(
              onPressed: () {
                setState(() {
                  // **The Condition**
                  if ('.'.allMatches(_text.text).length > 1 &&
                      ('+'.allMatches(_text.text).length > 1 ||
                          '-'.allMatches(_text.text).length > 1)) {
                    _validate = true;
                  } else {
                    _validate = false;
                  }
                });
              },child: Text('Submit'),textColor: Colors.white,color: Colors.blueAccent,)
          ],);
  }
}