This is the seventh day of my participation in the August More text Challenge. For details, see: August More Text Challenge

TextField

As the name suggests, the TextInput field is similar to UITextField in iOS, EditText in Android, and TextInput in the Web. Mainly for the user to provide input text to provide convenience. I’m sure you’ve all used this feature on the native client, so I’m not going to go into details about how TextField is used in Flutter.

The following has been updated to Github

TextField constructor:

Const TextField({Key Key, this.controller, // controller, control TextField text this.focusNode, this. TextInputType keyboardType: textinputType.text, // Input type this.style, this.textalign: Autofocus: false, this. autotext: false, // Enter this.autocorrect: true, this.maxLines: 1, this.maxLength, this.maxLengthEnforced: This.onchanged, // This. OnSubmitted, // This. OnEditingComplete, This.inputformatters, this.enabled, this.cursorWidth = 2.0, this.cursorRADIUS, this.cursorColor, this.cursorWidth = 2.0, this.cursorRadius, this.cursorColor, this.keyboardAppearance, })Copy the code

Let’s start with the basic TextField:

/ * * Created by Eunice li original on 2018/9/7. * email: [email protected] * * / import 'package: flutter/material. The dart'; class TextFieldAndCheckPage extends StatefulWidget { @override State<StatefulWidget> createState() => TextFieldAndCheckPageState(); } class TextFieldAndCheckPageState extends State<TextFieldAndCheckPage> { @override Widget build(BuildContext context) { Return Scaffold(appBar: appBar (title: Text(' input and select '),),body:TextField(),); }}Copy the code

This is the default input field that we’ve done nothing with. And then we’re going to try its properties

TextField(keyboardType: TextInputType. Number, decoration: InputDecoration(contentPadding: EdgeInsets. All (10.0), icon: Icon(icons.text_fields), labelText: 'Please enter your name)', helperText:' Please enter your real name ',), onChanged: _textFieldChanged, Autofocus: false, ), void _textFieldChanged(String str) { print(str); }Copy the code

We’re going to add a keyboardType property, and we’re going to set keyboardType to textinputType.number and you can see that every time we put a TextField in focus the keyboard pops up with a number first. Then we make some other effects for the input box, such as prompt text, icon, label text, etc. We added the decoration property to the above code and set the relevant property. You can see that when our TextField gets focus, the icon will automatically change color and the prompt text will automatically move up.

You can also see that I added onChanged. OnChanged is a callback triggered by each text change in the input box, and onSubmitted is a callback triggered by a user submission. Whenever the user changes the text in the input box, the current string is printed in the console. Same as onSubmitted.

Next, let’s implement a simple landing page:

/ * * Created by Eunice li original on 2018/9/7. * email: [email protected] * * / import 'package: flutter/cupertino. Dart'; import 'package:flutter/material.dart'; class TextFieldAndCheckPage extends StatefulWidget { @override State<StatefulWidget> createState() => TextFieldAndCheckPageState(); } class TextFieldAndCheckPageState extends the State < TextFieldAndCheckPage > {/ controller TextEditingController/cell phone number phoneController = TextEditingController(); PassController = TextEditingController(); @override Widget build(BuildContext context) {return Scaffold(appBar: appBar (title: Text(' input and select '),), body: Column( children: <Widget>[ TextField( controller: phoneController, keyboardType: TextInputType.number, decoration: InputDecoration(contentPadding: edgeInsets.all (10.0), Icon: Icon(iconicon.phone), labelText: 'Please enter your username ', helperText: 'Please enter your registered phone number ',), AutoFocus: false,), TextField(Controller: passController, keyboardType: Textinputtype. number, decoration: InputDecoration(contentPadding: edgeinset. all(10.0), icon: Icon(icons.lock), labelText: 'Please enter password ',), obscureText: true), RaisedButton(onPressed: _login, child: Text(' login '),),],),); } void _login() { print({'phone': phoneController.text, 'password': passController.text}); if (phoneController.text.length ! = 11) {showDialog(context: context, builder: (context) => AlertDialog(title: Text(' Text '),)); } else if (passController.text.length == 0) { showDialog( context: context, builder: (context) => AlertDialog( title: Text(' Please fill in the password '),)); } else {showDialog(context: context, builder: (context) => AlertDialog(title: Text(' login succeeded '),)); phoneController.clear(); } } void onTextClear() { setState(() { phoneController.clear(); passController.clear(); }); }}Copy the code

On the layout, we use a Column containing two Textfields and a RaisedButton. Logically, each time we click the button below, we determine whether the user name and password are correct and use the controller to clear the entered user name and password.

If the user enters a mobile phone number that is not 11 digits, a message is displayed indicating that the format of the mobile phone number is incorrect. If the user does not enter a password, a message is displayed indicating that the user has logged in successfully.

After I successfully logged in here, I also called a method: phonecontroller.clear () to clear the user name input box.

The logic of the code is simple. Other usages of TextField will not be introduced one by one, interested partners can try it themselves.

Use decoration to beautify the input box

First look at the effect:

Code:

TextField( controller: accountController, decoration: InputDecoration( border: OutlineInputBorder(), hintText: 'Please enter account number ', labelText:' top left ', prefixIcon: Icon(icon.person),),)Copy the code

As you can see, I’ve added a decoration property first.

Decoration Property Description:

Border: add a border, hintText: prompt text in the input box when no text is entered, prefixIcon: control on the left side of the input box, labelText: a prompt text. SuffixIcon: icon on the right side of the input box. Icon: Add an icon on the left side of the input box

Toggle focus in multiple input boxes

Introduce the onEditingComplete method:

Called when the user submits editable content (for example, when the user presses the “Done” button on the keyboard).

The default implementation of onEditingComplete performs two different actions depending on the situation:

  • When the completion operation is pressed, such as “done”, “go”, “send”, or “search”, the user’s content is submitted to [Controller] and the focus is abandoned.
  • When an unfinished action (such as “Next” or “Previous”) is pressed, the user’s content is submitted to [Controller] without giving up focus, because the developer might want to immediately move the focus to another input widget in [onSubmit].

We sometimes need such a situation, such as a login page, need to enter the account and password, naturally after entering the account to enter the password, we at the end of the input account, let the password input box to get the focus.

Take a look at the code:

. FocusNode secondTextFieldNode = FocusNode(); . Column( children: <Widget>[ TextField( /* onChanged: (text) { value = text; print(value); },*/ autofocus: Textcontroller: _textController, decoration: InputDecoration(suffixIcon: Icon(icon.chevron_right), // Icon on the right side of the input box Icon: Icon(icon.person), // prefixIcon on the left side of the input box: Icon(Icons. Skip_previous), // labelText: 'labelText', hintText: 'hintText', helperText: 'helperText', ), onEditingComplete: () => FocusScope.of(context).requestFocus(secondTextFieldNode), ), TextField( focusNode: SecondTextFieldNode, decoration: InputDecoration(contentPadding: EdgeInsets. Symmetric (HORIZONTAL: 15.0)),),),Copy the code

I created a junction at the top level and attached it to the second input box, which I used in the first input box’s onEditingComplete method

FocusScope.of(context).requestFocus(secondTextFieldNode),
Copy the code

Method to get the second input field to ask for focus, or you can add a button and click to perform this method to switch the focus function.

For example: [External link image dump failure, the source site may have anti-link mechanism, you are advised to save the image directly upload (img-BjsyHYMC-1573730655449)(cdn-images-1.medium.com/max/800/1*v…)] The code is simple, so I won’t post it.

keyboardType

The type of keyboard displayed when TextField becomes the focus.

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

Types are:

  • Textinputtype.text (normal full keyboard)
  • Textinputtype.number (numeric keypad)
  • TextInputType. EmailAddress (normal keyboard) with the “@”
  • Textinputtype.datetime (numeric keypad with “/” and “:”)
  • Textinputtype.multiline (with option to enable a numeric keypad in signed and decimal mode)

TextInputAction

Changing the textInputAction of the TextField can change the action button of the keyboard itself.

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

This causes the “Done” button to be replaced by the “Search” button:

TextCapitalization

TextField provides some options on how to capitalize letters in user input.

  • TextCapitalization. Sentences: this is the normal type of capital we expect, capitalize the first letter of each sentence.

  • TextCapitalization. Characters: uppercase all characters in the sentence.

[External link picture dump failed, the source may have anti-theft mechanism, it is recommended to save the picture directly upload (img-4ykahgu0-1573730655451)(cdn-images-1.medium.com/max/800/1*S…)]

  • Text3%. Words: Capitalize the first letter of each word.

Change the cursor in TextField

You can customize cursors directly from the TextField widget.

You can change the corner cursor color, width and radius. For example, here I have no obvious reason to make a circular red cursor.

TextField(cursorColor: color.red, cursorRadius: radius.circular (16.0), cursorWidth: 16.0,),Copy the code

Controls the size and maximum length of a TextField

TextFields control the maximum number of characters that can be written into them, the maximum number of lines, and the expansion when typing text.

TextField(
  maxLength: 4,
),
Copy the code

By setting the maxLength property, the maximum length is enforced and a counter is added to the TextField by default.

Making the source code