Effect:

Finally, we’re going after TextField, the Widget with the most properties and the most function points.

Basic attributes

TextField is a material design style input box, which has a variety of properties. In addition, the InputDecoration also has a variety of properties, but they are relatively simple, so don’t worry about it. Let me explain.

Take a look at the source code. Important or commonly used attributes are commented.

TextField

const TextField({ Key key, This. controller,// Controller this.focusNode,// Focus this.decoration = const InputDecoration(),// Decorate TextInputType KeyboardType,// keyboardType, The input type enclosing textInputAction, / / keyboard button this. TextCapitalization = textCapitalization. None, / / case enclosing style, / / style This.strutstyle, this.textalign = textalign.start,// Align this.textDirection, This. autofocus = false,// autofocus this.obscureText = false,// Whether to hide text, This. Autocorrect = true,// autocorrect this. MaxLines = 1,// Maximum number of lines, This. MinLines,// minLines this. {} = false, this. MaxLength,// Max input number, Have value after the bottom right hand corner there will be a counter this. MaxLengthEnforced = true, enclosing onChanged, / / input change callback enclosing onEditingComplete, / / input is completed, OnSubmitted // If this. Enabled is enabled, enter TextInputAction this.inputFormatters // If this This. cursorWidth = 2.0,// cursorWidth this.cursorRadius,// cursorWidth this.cursorColor,// cursorColor this.keyboardAppearance, This. ScrollPadding = const edgeinsets.all (20.0), this. DragStartBehavior = DragStartBehavior.start, Enclosing enableInteractiveSelection, enclosing onTap, / / click event enclosing buildCounter, enclosing scrollPhysics,})Copy the code

Many parameters, in fact, in daily development even half of the attributes are not used, but I will try to introduce as much as possible.

InputDecoration

Const InputDecoration({this.icon,// this. LabelText, const InputDecoration({this.icon,// This. HintText this.labelStyle,// Float the text style this.helperText,// help text this.helperStyle, this.hintText,// input the text prompt this.hintStyle, HintMaxLines, this.errorText,// error: this.errorStyle, this.errorMaxLines, Enclosing hasFloatingPlaceholder = true, / / whether show this. The suspension prompt letter isDense, This. ContentPadding,// Fill this. PrefixIcon,// left inside the icon this.prefix, this.prefixText,// left inside the text this.prefixStyle, Suffix, this.suffixText, this.suffixStyle, Counter,// customize counter this.counterText,// count text this.counterStyle,// count style this.filled,// fill this. FillColor,// fillColor this.errorBorder, this.focusedBorder, this.focusedErrorBorder, this.disabledBorder, this.enabledBorder, This border, / / frame enclosing enabled = true, enclosing semanticCounterText, enclosing alignLabelWithHint,})Copy the code

Many parameters, mostly a small function point icon, text and style, are not complex.

Ok, basic attributes roughly go through, mind have an impression on the line. Now let’s do the real thing.

style

Basic style

			TextField(),
Copy the code

Very simple, no parameters, of course the effect is very simple.

Style can modify styles.

Hidden text

Example Modify the obscureText property value

              TextField(
                obscureText: true,
              ),
Copy the code

You can see that the input is no longer visible and has become a common password type.

The keyboard type

Keyboard types are input types, such as number, which can only be entered as numbers

              TextField(
                keyboardType: TextInputType.number,
              ),
Copy the code

TextInputType Optional type:

  • text
  • multiline
  • number
  • phone
  • datetime
  • emailAddress
  • url

The keyboard button

The button in the lower right corner of the keyboard, commonly known as done, is a finished check button, as shown in the picture above.

              TextField(
                textInputAction: TextInputAction.done,
              ),
Copy the code

TextInputAction Other options:

  • none
  • unspecified
  • done
  • go
  • search
  • send
  • next
  • previous
  • continueAction
  • join
  • route
  • emergencyCall
  • newline

case

That is, to control the case of the English letter input, such as the first letter of a word uppercase

              TextField(
                textCapitalization: TextCapitalization.words,
              ),
Copy the code

Other options for Text3% :

  • Words: Capitalize the first letter of a word
  • Capitalize the first letter of the sentence
  • Characters: all letters are capitalized
  • None: Default none

The cursor

The default is a blue vertical line

              TextField(
                cursorColor: Colors.orange,
                cursorWidth: 15,
                cursorRadius: Radius.circular(15),
              ),
Copy the code

Maximum number of lines

Set a maximum of 3 lines

              TextField(
                maxLines: 3,
              ),
Copy the code

As you can see, the TextField height has become 3 lines. But WHAT if I just want to enter at most 3 lines and default to 1 line height? Don’t panic, just add one argument: minLines

              TextField(
                maxLines: 3,
                minLines: 1,
              ),
Copy the code

As you can see, the height of the TextField is adaptive.

counter

There’s going to be a count in the lower right hand corner

              TextField(
                maxLength: 8,
              ),
Copy the code

Default: current input length/maximum length, so can we change this place, of course, the following simple operation

TextField(maxLength: 8, decoration: InputDecoration(counter: Text(" custom count 0/100"),),Copy the code

Here, I use the counter under the InputDecoration. The type is widget, so the expansion is quite high. I only use a Text, and other widgets are also ok.

For pure text, there is also a counterText attribute and counterStyle under InputDecoration.

icon

There are three types of ICONS:

  • The icon outside the left
              TextField(
                decoration: InputDecoration(
                  icon: Icon(Icons.person),
                ),
              ),
Copy the code

  • Left inside icon
              TextField(
                decoration: InputDecoration(
                  prefixIcon: Icon(Icons.phone_android),
                ),
              ),
Copy the code

  • Inside icon on the right
TextField( decoration: InputDecoration( suffixIcon: IconButton( icon: Icon(Icons.close), onPressed: () { controller.clear(); },),),),Copy the code

Add an IconButton to the right icon, because of the click event, we can clear the contents of the TextField when clicking.

This is the introduction of ICONS. In addition to ICONS, the corresponding position can also display text or custom display other widgets. For example, prefixIcon has three other properties, which are used in the same way as the custom counter described above.

    this.prefix,
    this.prefixText,
    this.prefixStyle,
Copy the code

Prompt words

There are four types of prompt text:

  • Enter prompt text
TextField(Controller: controller, decoration: InputDecoration(hintText: 'please input id aaa',),Copy the code

  • Hover prompt text
TextField(Controller: controller, decoration: InputDecoration(hintText: 'please input id ', labelText:' please input id ',),Copy the code

As you can see, labelText is displayed by default and hintText is displayed after focus, so labelText can replace hintText.

  • Help text
TextField(Controller: Controller, decoration: InputDecoration(helperText: "help ", helperStyle: TextStyle(color: Colors.blue) ), ),Copy the code

It’s always on the bottom left

  • Error text
TextField(Controller: Controller, decoration: InputDecoration(errorText: "You didn't enter anything ",),),Copy the code

Remove underline

TextField (decoration: InputDecoration. Collapsed (hintText: "no underline the input box"),),Copy the code

It can also be decoration: null, the difference is no hintText

A border

              TextField(
                decoration: InputDecoration(
                  border: OutlineInputBorder(),
                ),
              ),
Copy the code

If you don’t like the rounded corner, you can change it, for example:

              TextField(
                decoration: InputDecoration(
                  border: OutlineInputBorder(
                    borderRadius: BorderRadius.all(Radius.circular(30)),
                  ),
                ),
              ),
Copy the code

Get input

There are two ways:

  • onChanged

OnChanged is a callback to input changes and returns a String value that can be remembered as a variable

TextField(onChanged: (text) {print(" input changed "+ text); },),Copy the code
  • controller

That is, the controller, initialized:

  var controller;

  @override
  void initState() {
    super.initState();
    controller = TextEditingController();
    controller.addListener(() {});
  }
Copy the code

Configuration to the TextField

              TextField(
                controller: controller,
              ),
Copy the code

Access to content

controller.text
Copy the code

Calling controller.text in the event returns the input.

Close the soft keyboard

Often we need to turn off the soft keyboard when submitting in an event

Here we use the focusNode

Initialization:

FocusNode userFocusNode = FocusNode();
Copy the code

Configuration:

              TextField(
                focusNode: userFocusNode,
              ),
Copy the code

Then call it where needed:

userFocusNode.unfocus();
Copy the code

check

It actually has an inputFormatters property

  final List<TextInputFormatter> inputFormatters;
Copy the code

TextInputFormatter source code, there are three subclasses:

  • BlacklistingTextInputFormatter
  • WhitelistingTextInputFormatter
  • LengthLimitingTextInputFormatter

Blacklist, whitelist and length limit, we just find a look at the source code is how to achieve verification:

If you look down, you’ll see this code:

  static final BlacklistingTextInputFormatter singleLineFormatter
      = BlacklistingTextInputFormatter(RegExp(r'\n'));
Copy the code

The key word is RegExp, which is just regular expressions we use in general.

In this way, we can also customize the verification rules, such as the verification of mobile phone number:

String validateMobile(String value) { String patttern = r'(^[0-9]*$)'; RegExp regExp = new RegExp(patttern); If (value.length == 0) {return "Phone number is empty "; } else if (! RegExp. HasMatch (value)) {return "Invalid phone number format "; } return null; }Copy the code

The above is just our general verification, it is still recommended to use From to wrap TextFormField for forms

abnormal

  • Soft keyboard pops up after cover
  • Soft keyboard after the high overflow

Solution: Wrap it around a sliding component (ListView, etc.) so that when the soft keyboard pops up, the input box automatically slides up.


conclusion

The above is all introduced, and then write a small demo login registration:

Making:Github.com/yechaoa/wan…

The official document: API. Flutter. Dev/flutter/mat…


Writing is not easy, just click “like” or “star” whenever it is useful