preface

Recently, I wanted to start a flutter project. At first, I copied the chat tool according to Flutter_wechat, but I didn’t know much about many details in it. For a little person like me who just got to know flutter, I always felt that I was willing but unable to do enough. The next best thing was to create a gold-digging blog based on the gold-digging UI and API

In traditional HTML, we usually do form validation with form forms, and flutter is the same

Form component API

Here, I put the Form component Api directly here:

Form

The Form inherits from the StatefulWidget object, and its corresponding state class is FormState. Let’s first look at the Form class definition:

Form({
  @required Widget child,
  bool autovalidate = false,
  WillPopCallback onWillPop,
  VoidCallback onChanged,
})
Copy the code
  • autovalidate: Whether to automatically verify input content; As for thetrueWhen the content of each sub-formField changes, the validity is automatically verified and error messages are displayed directly. Otherwise, you need to callFormState.validate()To check manually.
  • onWillPop: determineFormWhether the route can be returned directly (e.g., by clicking the back button), the callback returns oneFutureObject if the end result of the Future isfalse, the current route does not return. If it istrue, the system returns to the previous route. This property is typically used to intercept the back button.
  • onChanged:FormAny child ofFormFieldThis callback is triggered when the content changes.

FormField

FormField is an abstract class that defines several properties through which FormState internally performs operations. FormField is partially defined as follows:

const FormField({ ... FormFieldSetter<T> onSaved, // Save the callback FormFieldValidator<T> // Initial value bool autovalidate = false, // Whether automatic verification is enabled. })Copy the code

For ease of use, Flutter provides a TextFormField component that inherits from the FormField class and is also a wrapper class for TextField, so it also includes the properties of TextField in addition to the properties defined by FormField.

FormState

FormState is the State class for the Form, available via form.of () or GlobalKey. We can use it to operate uniformly on a Form descendant, FormField. Let’s look at three commonly used methods:

  • FormState.validate(): is called after this method is calledFormThe childrenThe FormField validateReturns false if any verification fails, and all verification failures are returned with an error message.
  • FormState.save(): is called after this method is calledFormThe childrenFormFieldthesaveCallback to save form content
  • FormState.reset(): When this method is called, descendants are generatedFormFieldContent empty.

Specific operation

Therefore, using the form form for form validation, we mainly have the following three steps

  • Constructing the Form form
  • Check the function
  • Check is triggered when clicked

Constructing the Form form

final _formKey = GlobalKey<FormState>();
TextEditingController _uNameController = new TextEditingController();
TextEditingController _pwdController = new TextEditingController();
Copy the code

Check the function

Here we only put part of the code to verify the phone number

Class ValidatorUtils {static bool isMobileExact(String input) {return matches(RegexConstants.REGEX_MOBILE_EXACT, input); } /// returns whether the input matches the regular expression. static bool matches(String regex, String input) { if (input.isEmpty) { return false; } return RegExp(regex).hasMatch(input); } } class RegexConstants{ static const String REGEX_MOBILE_EXACT = "^((13[0-9])|(14[579])|(15[0-35-9])|(16[2567])|(17[0-35-8])|(18[0-9])|(19[0-35-9]))\d{8}$"; }Copy the code

Click the button to trigger verification

onTap: If ((_formkey.currentState as FormState).validate()) {print(_unamecontroller.text); print(_pwdController.text) } },Copy the code

The complete form code is shown below

import 'package:flutter/cupertino.dart'; import 'package:flutter/material.dart'; import 'package:flutter_application/pages/common/bar/common_bar.dart'; import 'package:flutter_application/pages/common/button/common_button.dart'; import 'package:flutter_application/utils/validator_utils.dart'; class LoginPage extends StatefulWidget { @override _LoginState createState() => _LoginState(); } class _LoginState extends State<LoginPage> { @override Widget build(BuildContext context) { final _formKey = GlobalKey<FormState>(); TextEditingController _uNameController = new TextEditingController(); TextEditingController _pwdController = new TextEditingController(); Return new Scaffold (resizeToAvoidBottomInset: false, / / keyboard pop-up extrusion problems caused by the appBar: CommonBar (title: 'Login'), the body: Container(padding: EdgeInsets. FromLTRB (12.0, 12, 12.0, 0), Child: Column(children: [ Image.asset('assets/images/juejin_logo.png'), Form( key: _formKey, child: Column( mainAxisAlignment: MainAxisAlignment.start, children: <Widget>[ TextFormField( controller: _uNameController, decoration: InputDecoration(labelText: 'user name ', hintText:' phone number ', // Email icon: icon (CupertinoIcons. Person)), validator: (value) {bool status = the ValidatorUtils. IsMobileExact (value!); the if (! Status) {return 'please enter the correct phone number;} return null;},), TextFormField(Controller: _pwdController, obscureText: true, decoration: InputDecoration(hintText: 'password ', labelText: Container(margin: EdgeInsets. FromLTRB (0, 50, 0, 0), child: CommonButton(text: 'login ', onTap: If ((_formkey.currentState as FormState).validate()) {print(_unamecontroller.text); print(_pwdController.text) } }, ), ) ], ), ) ], )), ); }}Copy the code