簡體   English   中英

自定義驗證 TextFormField Flutter

[英]Custom Validation TextFormField Flutter

我里面有 Form 和 TextFormField :

 new Expanded(
  child: TextFormField(
    style: new TextStyle(color: Colors.white),
    keyboardType: TextInputType.text,
    validator: (String value) {
      if (value.length <= 5) {
       //Show error as a Snackbar
      }
    },
    onSaved: (String value) {},

  ),
)

在按下按鈕時,我正在檢查是否所有字段都經過驗證:

 if (_formKey.currentState.validate()) {
      _submit();
 }

現在的問題是當您調用validate()並且不在validate()方法中返回任何文本時,它會認為它返回 true。

我不想在 textField 下方顯示錯誤,而是作為 Snackbar。

此外,我嘗試在每個驗證器方法中設置一個額外的標志和設置,但如果表單中有多個字段,它會變得復雜。

誰能告訴我如何處理這種_formKey.currentState.validate()應該返回 false 並且 TextFormField 中的驗證器方法不需要返回錯誤文本的情況。

您不應該使用Form小部件和TextFormField在 TextField 中顯示錯誤。

改為由控制器進行驗證

例如

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>[
            Text('Error Showed if Field is Empty on Submit button Pressed'),
            TextField(
              controller: _text,
              decoration: InputDecoration(
                labelText: 'Enter the Value',
              ),
            ),
            RaisedButton(
              onPressed: () {
                        if(_text.text.length<=5){
                    // open dialog
                  }
              },
              child: Text('Submit'),
              textColor: Colors.white,
              color: Colors.blueAccent,
            )
          ],
        ),
      ),
    );
  }
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM