Detailed use of Flutter TextField

TextField is used for text input and provides a number of properties. Here’s how to use this widget.

Flutter TextField development document

1. The attribute

const TextField({
    Key key,
    this.controller, 
    this.focusNode,
    this.decoration = const InputDecoration(),
    TextInputType keyboardType,
    this.textInputAction,
    this.textCapitalization = TextCapitalization.none,
    this.style, // Text style
    this.strutStyle,
    this.textAlign = TextAlign.start, // Align text horizontally
    this.textAlignVertical, // This text is vertically aligned
    this.textDirection, // Text direction
    this.readOnly = false.// Whether it is read-only
    ToolbarOptions toolbarOptions,
    this.showCursor,
    this.autofocus = false.this.obscureText = false.this.autocorrect = true.this.enableSuggestions = true.this.maxLines = 1.this.minLines,
    this.expands = false.this.maxLength,
    this.maxLengthEnforced = true.this.onChanged, // The content has changed the method callback
    this.onEditingComplete, // Complete the edit method callback. With this method implemented, the keyboard will no longer collapse automatically
    this.onSubmitted, // Commit method callback
    this.inputFormatters,
    this.enabled,
    this.cursorWidth = 2.0.// Cursor width
    this.cursorRadius, // The cursor is rounded
    this.cursorColor, // Cursor color
    this.keyboardAppearance,
    this.scrollPadding = const EdgeInsets.all(20.0), 
    this.dragStartBehavior = DragStartBehavior.start,
    this.enableInteractiveSelection = true.this.onTap, // Click method callback (start editing)
    this.buildCounter, // (BuildContext context, {int currentLength, int maxLength, bool isFocused,}) {} counter callback
    this.scrollController, / / rolling
    this.scrollPhysics,
  })
Copy the code
1.1 the controller

Edit box controller, through which you can set/get the content of the edit box, select the edit content, listen to edit text change events. In most cases we need to explicitly provide a Controller to interact with the text box. If no Controller is provided, one is automatically created inside the TextField.

1.1.1 TextEditingController

The official documentation

class _YXCContentState extends State<YXCContent> {

  final TextEditingController _editingController = TextEditingController();

  @override
  void initState() {
    super.initState();
    // Add a listener
    _editingController.addListener((){
      print("addListener() -- ${_editingController.text}");
      final text = _editingController.text.toLowerCase();
      _editingController.value = _editingController.value.copyWith(
        text: text,
      );
    });
  }

  @override
  void dispose() {
    / / release
    _editingController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {

    return Container(
      padding: EdgeInsets.only(left: 20, right: 20), child: Center( child: TextField( controller: _editingController, ), ), ); }}Copy the code

This code uses the TextEditingController to listen for TextField input and convert all input letters to lowercase

Note: Don’t forget to releaseTextEditingController

Remember to dispose of the TextEditingController when it is no longer needed. This will ensure we discard any resources used by the object.

1.2 focusNode

Used to control whether the TextField occupies the input focus of the current keyboard and can be used to handle keyboard events

class _YXCContentState extends State<YXCContent> {
  // focusNode
  final FocusNode _focusNode = FocusNode(debugLabel: "Button");

  @override
  void initState() {
    super.initState();
    // Focus listener
    _focusNode.addListener(() {
      if (_focusNode.hasFocus == true) {
        print("Input box in focus");
      } else {
        print("Input box loses focus"); }}); }@override
  void dispose() {
    _focusNode.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      padding: EdgeInsets.only(left: 20, right: 20),
      child: Column(
        children: <Widget>[
          Center(
            child: TextField(
              focusNode: _focusNode,
            ),
          ),
          FlatButton(
            onPressed: () {
              if (_focusNode.canRequestFocus) {
                FocusScope.of(context).requestFocus(_focusNode);
              }
            },
            child: Text('Keyboard up'),
          ),
          MaterialButton(
            onPressed: () {
              _focusNode.unfocus();
            },
            child: Text('Put away the keyboard'() [() [(); }}Copy the code

TextField focus control (keyboard up and down) by clicking a button

1.3 decoration

Used to control the appearance Settings of the TextField, such as prompts, background colors, borders, and so on

const InputDecoration({
    this.icon, // Add a Widget to the left
    this.labelText, // The top description string will change if the input box becomes the focus
    this.labelStyle, // Set the text style for the top description
    this.helperText, // Bottom description text
    this.helperStyle, // Describe the text style at the bottom
    this.helperMaxLines, // Maximum number of lines of bottom description text
    this.hintText, // Placeholder text, similar to the iOS placeholder, will only appear when the input box has no input and is in focus
    this.hintStyle, // Placeholder text style
    this.hintMaxLines, // The maximum number of lines of placeholder text
    this.errorText, // Error message. If helperText is set at the same time, errorText takes precedence
    this.errorStyle, // Error with text style
    this.errorMaxLines, // Error text prompt maximum number of lines
    this.hasFloatingPlaceholder = true.// Sets whether to display labelText. If set to false, labelText is not displayed when TextField is in focus, and is displayed when TextField is not in focus
    this.isDense,
    this.contentPadding, // Set the padding of the content. After setting the padding, the content of the input box, helperText, counterText, and errorText will be affected
    this.prefixIcon, // A Widget between icon and prefix (prefixText)
    this.prefix, If prefixIcon is set at the same time, it will be placed after the prefixIcon
    this.prefixText, PrefixText cannot be set if prefix is set, the two are in conflict
    this.prefixStyle, // Set the text style
    this.suffixIcon, // Similar to prefixIcon, except at the end
    this.suffix, / / similar to suffix
    this.suffixText, // Similar to prefixText, suffix cannot be set at the same time
    this.suffixStyle, // suffixText style
    this.counter, // Display the counter Widget first if counterText is also set
    this.counterText, // Count text displays
    this.counterStyle, // Count text styles
    this.filled, // Whether the container needs to be decorated
    this.fillColor, // Set the color of the container
    this.focusColor, // 
    this.hoverColor, // 
    this.errorBorder, // The input box is incorrectly typed and does not become the focus border display style
    this.focusedBorder, // The input box is in focus and the errorText presentation style is not set
    this.focusedErrorBorder, // When errorText is set, the input becomes the focus border display style
    this.disabledBorder, // The border style is used when the input box is not available
    this.enabledBorder, // The input box can be used when the border display style is not in focus
    this.border, // Set the border style with a lower priority than other borders. If you need to set no border style, use inputBorder-none
    this.enabled = true.// Set whether the input box is available
    this.semanticCounterText,
    this.alignLabelWithHint,
  }) : assert(enabled ! =null),
       assert(! (prefix ! =null&& prefixText ! =null), 'Declaring both prefix and prefixText is not supported.'),
       assert(! (suffix ! =null&& suffixText ! =null), 'Declaring both suffix and suffixText is not supported.'),
       isCollapsed = false;
Copy the code
1.3.1 border

Set a borderless style

final InputDecoration _decoration = InputDecoration(
  border: InputBorder.none, // No border Settings
);
Copy the code
1.3.2 UnderlineInputBorder (Border underline Style)
enabledBorder: UnderlineInputBorder(
    borderSide: BorderSide(
    color: Colors.red,
    width: 5,
    style: BorderStyle.none, // Hide the border),),Copy the code
1.3.3 OutlineInputBorder (Border wrap)
focusedBorder: OutlineInputBorder(
      borderSide: BorderSide(
        color: Colors.orange,
        width: 3,
    ),
  borderRadius: BorderRadius.circular(10),
  gapPadding: 20.// Set the spacing between labelText and the border
),
Copy the code

1.4 keyboardType (Keyboard Style)

There are the following keyboard types (some are tested and found not to make much difference)

static const List<String> _names = <String> ['text'.'multiline'.'number'.'phone'.'datetime'.'emailAddress'.'url'.'visiblePassword',];Copy the code
1.5 textInputAction

Sets the display style of return, with the following enumerated values

enum TextInputAction {
  none, // No keyboard
  unspecified, / / a newline
  done, / / finish
  go, / / to
  search, / / search
  send, / / send
  next, / / the next step
  previous, // No response on iOS
  continueAction, / / to continue
  join, / / to join
  route, / / route
  emergencyCall, // Emergency call
  newline, / / a newline
}
Copy the code
1.6 textCapitalization

Sets the case of the platform keyboard

enum TextCapitalization {
  words, // Capitalize each word
  sentences, // The first letter is uppercase, all the others are lowercase
  characters, // The default letter is uppercase
  none, // Default lowercase keyboard
}
Copy the code
1.7 strutStyle

Styles text paragraphs

1.7.1 StrutStyle

The following properties

const StrutStyle({
    String fontFamily, // The font name
    List<String> fontFamilyFallback, // fontFamily searches for an ordered list of font names when the font cannot be found
    this.fontSize, // Font size
    this.height, // Set the height of each row to scale
    this.leading, // Set the spacing of each line, also calculated in proportion
    this.fontWeight,
    this.fontStyle,
    this.forceStrutHeight,
    this.debugLabel,
    String package,
}) : fontFamily = package == null ? fontFamily : 'packages/$package/$fontFamily',
      _fontFamilyFallback = fontFamilyFallback,
      _package = package,
      assert(fontSize == null || fontSize > 0),
      assert(leading == null || leading >= 0),
      assert(package == null|| (package ! =null&& (fontFamily ! =null|| fontFamilyFallback ! =null)));
Copy the code
1.8 cursorWidth

Set the cursor width

1.9 cursorColor

Set the cursor color

1.10 scrollController

When the input box can scroll, it is used to listen for scroll events

1.10.1 ScrollController

Scrolllisten on input fields via ScrollController

class _YXCContentState extends State<YXCContent> {

  final FocusNode _focusNode = FocusNode();

  final ScrollController _scrollController = ScrollController();
  final TextEditingController _editingController = TextEditingController(
    text: "Rain in June"
        "A rain has kept me here."
        "Your cold face will break my heart."
        "June rain is you."
        "With little drops of pain in my heart."
        "Oh~ I can't believe you didn't mean it"
        "Why did you leave me in the storm?"
        "Oh~ I don't have the heart and I don't want to betray you"
        "Just waiting for you to change your mind."
        "I haven't given up and I'm not leaving you."
        "I'll wait for you even if I have to."
        "I will wait for you with all my heart."
        "One day you'll believe me and I love you."
        "Miss you in the rain."
        "Nothing in my heart can compare to that."
        "When you were gone, everything was lost in the rain."
        "I miss you, I love you, I love you.",);@override
  void initState() {
    _scrollController.addListener((){
      print("${_scrollController.offset.toString()}");
    });

    super.initState();
  }

  @override
  void dispose() {
    _focusNode.dispose();
    _scrollController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {

    return Container(
      padding: EdgeInsets.only(left: 20, right: 20),
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: <Widget>[
          Center(
            child: Container(
              height: 100,
              child: TextField(
                focusNode: _focusNode,
                scrollController: _scrollController,
                controller: _editingController,
                maxLines: null,
              ),
            ),
          ),
          FlatButton(
              onPressed: () {
                _focusNode.unfocus();
              },
              child: Text('End edit')),,),); }}Copy the code

Oneself grope, have incorrect place, welcome big guy to point out!!