Flutter Actual Warfare] Text Components and Five Cases

Hello, Lao Meng: This is the second in a series of articles about text components, which include text display components (Text and RichText) and text input components (TextField), basic usage and five cases to help you master them quickly. First link: The History of Mobile Technology

Text

Text is a component for displaying text, not one of the most common components.The basic usage is as follows:

Text('Lao Meng')

Note: The Text component must be wrapped under the Scafold component, otherwise the effect is as follows:

The style of the text is set in the style, the type is TextStyle, TextStyle contains a number of text style attributes, some of which are commonly used are described below.

Set the text size and color:

Text('Lao Meng',style: TextStyle(color: Colors.red,fontSize: 20),),

For comparison, the black font above has no effect set.

Set font size:

Text('Lao Meng',style: TextStyle(fontWeight: FontWeight.bold))

There are nine levels of font thickness, from w100 to w900.FontWeight.bold Is w700.

Set italics:

Text('Lao Meng',style: TextStyle(fontStyle: FontStyle.italic,))

Set a custom font:

  1. First download font libraries (such as Chinese font libraries)
  2. In projects where font files are copied, the general directory is assets/fonts/, assets, and fonts, which need to be created manually. This directory is not required, but is conventionally available and resources are typically placed in the assets directory.
  3. To configurePubspec.yaml:
fonts:
  - family: maobi 
    fonts:
      - asset: assets/fonts/maobi.ttf

maobi: is your own name for the current font, just meaningful.

asset: The directory of the font file.

Use:

Text('Lao Meng', style: TextStyle(fontFamily: 'maobi',)),

Set alignment:

Container(
  height: 100,
  width: 200,
  color: Colors.blue.withOpacity(.4),
  child: Text('Lao Meng', textAlign: TextAlign.center),
),

textAlign simply controls the alignment in the horizontal direction, with the values explained below:

  • Left: left aligned
  • Right: right alignment
  • center: centered
  • justify: aligned at both ends. There is a bug in this property in Chinese (Flutter version: 1.17.3) or it can be found in Focus on this issue in the official issue
  • start: Front-end alignment, related to TextDirection property, if set TextDirection.ltr Then left align, set TextDirection.rtl Align to the right.
  • end: end alignment, related to TextDirection property, if set TextDirection.ltr Then right align, set TextDirection.rtl Then align left.

Set text wrap:

Container(
  height: 100,
  width: 200,
  color: Colors.blue.withOpacity(.4),
  child: Text('Lao Meng, focus on sharing Flutter Technology and Application Actual Warfare',softWrap: true,),
)

Handling when text is out of range:

Container(
  height: 100,
  width: 200,
  color: Colors.blue.withOpacity(.4),
  child: Text('Lao Meng, focus on sharing Flutter Technology and Application Actual Warfare',overflow: TextOverflow.ellipsis,),
)

How overflow is handled:

  • Clip: clip directly.
  • fade: more and more transparent.
  • Ellipsis: End of ellipsis.
  • visible: Still shown, the parent component will overflow at this time.

Set global font style:

Set the following in the theme of MaterialApp

MaterialApp(
  title: 'Flutter Demo',
  theme: ThemeData(
   ...
    textTheme: TextTheme(
        bodyText2: TextStyle(color: Colors.red,fontSize: 24),
    )
  ),
  home: Scaffold(
    body: TextDemo(),
  ),
)

The Text component defaults to red,

Text('Lao Meng'),

Text('Lao Meng',style: TextStyle(color: Colors.blue,fontSize: 20),),

RichText

RichText has the same properties as Text, using the following:

RichText(
  text: TextSpan(
      style: DefaultTextStyle.of(context).style,
      children: <InlineSpan>[
        TextSpan(text: 'Lao Meng', style: TextStyle(color: Colors.red)),
        TextSpan(text: ','),
        TextSpan(text: 'Focus on sharing Flutter Technology and Application Actual Warfare'),
      ]),
)

TextField

TextField is a text input component, or input box, which is one of the common components.Basic usage:

TextField()

Without any parameters, the simplest text input component comes out as follows:

Decoration is the decoration (appearance) parameter of the TextField component and is of type InputDecoration.

The icon appears in front of the input box and is used as follows:

TextField(
  decoration: InputDecoration(
    icon: Icon(Icons.person),
  ),
)

When the input box is empty and has no focus, labelText appears at the top of the input box. When it gets focus or is not empty, labelText moves up a little. The labelStyle parameter represents the text style. Refer to TextStyle specifically for the following usage:

TextField(
  decoration: InputDecoration(
    labelText: 'Full name:',
    labelStyle: TextStyle(color:Colors.red)
  ),
)

The hasFloatingPlaceholder parameter controls whether labelText is also displayed when the input box gets focus or is not empty, defaulting to true, which is displayed.

The helperText appears at the lower left of the input box to prompt the user, and the helperStyle parameter represents the text style, with the following specific reference to TextStyle usage:

TextField(
  decoration: InputDecoration(
    helperText: 'User name length is 6-10 Letters',
    helperStyle: TextStyle(color: Colors.blue),
    helperMaxLines: 1
  ),
)

hintText is a hint when the input box is empty, not displayed when it is not empty, and is used as follows:

TextField(
  decoration: InputDecoration(
    hintText: 'enter one user name',
    hintStyle: TextStyle(color: Colors.grey),
    hintMaxLines: 1
  ),
)

ErorText is displayed at the bottom left of the input box. The default font is red and used as follows:

TextField(
  decoration: InputDecoration(
    errorText: 'User name input error',
    errorStyle: TextStyle(fontSize: 12),
    errorMaxLines: 1,
    errorBorder: OutlineInputBorder(borderSide: BorderSide(color: Colors.red)),
  ),
)

The components of the prefix series are in front of the input box and are used as follows:

TextField(
  decoration: InputDecoration(
    prefixIcon: Icon(Icons.person)
  ),
)

Note the difference between prefix and icon, where icon is outside the input box border and prefix is inside.

In contrast to prefix, suffix is used at the end of the input box as follows:

TextField(
  decoration: InputDecoration(
      suffixIcon: Icon(Icons.person)
  ),
)

The counter component counts the number of words in the input box. Counter just shows the effect. It does not have the function of counting words automatically. The code of counting words automatically is as follows:

var _textFieldValue = '';
TextField(
  onChanged: (value){
    setState(() {
      _textFieldValue = value;
    });
  },
  decoration: InputDecoration(
    counterText: '${_textFieldValue.length}/32'
  ),
)

When filled is true, the input box will be filled by fillColor, and the code of the QQ login input box is as follows:

Container(
  height: 60,
  width: 250,
  child: TextField(
    decoration: InputDecoration(
      fillColor: Color(0x30cccccc),
      filled: true,
      enabledBorder: OutlineInputBorder(
          borderSide: BorderSide(color: Color(0x00FF0000)),
          borderRadius: BorderRadius.all(Radius.circular(100))),
      hintText: 'QQ Number/Cell-phone number/mailbox',
      focusedBorder: OutlineInputBorder(
          borderSide: BorderSide(color: Color(0x00000000)),
          borderRadius: BorderRadius.all(Radius.circular(100))),
    ),
  ),
)

Controller is a text editing controller for input boxes. It can get the contents of TextField and set the contents of TextField. The following changes the input English to uppercase:

TextEditingController _controller;

@override
void initState() {
  super.initState();
  _controller = TextEditingController()
    ..addListener(() {
      //Get the contents of the input box to uppercase
      _controller.text = _controller.text.toUpperCase();

    });
}

@override
Widget build(BuildContext context) {
  return TextField(
    controller: _controller,
  );
}

@override
dispose() {
  super.dispose();
  _controller.dispose();
}

Sometimes the input box is followed by a Clear function, which requires a controller.If you need two TextFields for content synchronization, you only need to set the same controller for two TextFields.

The keyboardType parameter controls the type of soft keyboard as follows:

  • text: universal keyboard.
  • Multline: When TextField is multiline (maxLines set to greater than 1), the line break button is at the bottom right.
  • number: Numeric keyboard.
  • Phone: Mobile phone keyboard, more'*'and'#' than numeric keyboard.
  • datetime: like text on ios, the numeric keypad,':'and'-' appear on android.
  • emailAddress: Mailbox keyboard with'@'and'.' keys.
  • url: url keyboard with'/'and'.' keys.
  • visiblePassword: Keyboard with subtitles and numbers.

The textInputAction parameter controls the keys on the lower right corner of the soft keyboard as follows:

  • none:android displays return keys, not supported by ios.
  • unspecified: Let the operating system decide which one is appropriate. Normally, android displays Finish or Return.
  • Done: android shows the button representing "done", ios shows "Done".
  • Go:android displays an icon that indicates where the user is going, such as a right arrow, and ios displays Go.
  • Search: android shows the button that expresses the search, ios shows "Search".
  • Send:android displays buttons that express the meaning of sending, such as the paper plane button, and ios displays Send.
  • Next: android shows buttons that express "go forward", such as "arrow to the right", and ios shows "Next".
  • previous: android displays buttons that express "back", such as "arrow to the left", which ios does not support.
  • continueAction: android is not supported, IOS only displays "Continue" in ios9.0+.
  • Join: Android and ios show "Join".
  • Route: android is not supported, ios shows "Route".
  • EmergncyCall: not supported by android, ios shows "Emergency Call".
  • newline: android shows the button that says "line break" and ios shows "line break".

You may find that most of the buttons displayed on Android are indeterminate, such as the right arrows on next and the forward arrows on next, which are caused by the customization of Android ROM by major manufacturers.

The textCapitalization parameter configures whether the keyboard is uppercase or lowercase, and only supports text as the keyboard mode. This configuration is ignored in other modes as follows:

  • words: capitalize the first letter of each word.
  • sentences: capitalize the first letter of a sentence.
  • characters: capitalize each letter
  • none: all lowercase

Just to control whether the soft keyboard is in uppercase or lowercase mode, you can also switch between uppercase and lowercase, and the system will not change the contents of the input box.

textAlignVertical represents the alignment of the vertical direction, and textDirection represents the text direction, as follows:

TextField(
  textAlignVertical: TextAlignVertical.center,
  textDirection: TextDirection.rtl,
)

toolbarOptions stands for long-time pop-up menus, such as copy, cut, paste, selectAll, which are used as follows:

TextField(
  toolbarOptions: ToolbarOptions(
    copy: true,
    cut: true,
    paste: true,
    selectAll: true
  ),
)

Cursor represents the cursor and is used as follows:

TextField(
  showCursor: true,
  cursorWidth: 3,
  cursorRadius: Radius.circular(10),
  cursorColor: Colors.red,
)

The results are as follows:

Setting the input box to a password box requires only setting the obscureText property to true, as follows:

TextField(
  obscureText: true,
)

With inputFormatters, you can restrict what the user enters, such as only letters, as follows:

TextField(
  inputFormatters: [
    WhitelistingTextInputFormatter(RegExp("[a-zA-Z]")),
  ],
)

The user cannot enter a number at this time.

onChanged is a callback when the content changes, onSubmitted is a callback by clicking Enter or Complete on the soft keyboard, onTap callback by clicking the input box, as follows:

TextField(
  onChanged: (value){
    print('onChanged:$value');
  },
  onEditingComplete: (){
    print('onEditingComplete');
  },
  
  onTap: (){
    print('onTap');
  },
)

Word count is often required in the lower right corner of the input box. In addition to the method described above, buildCounter can also be used. It is recommended that this method be used as follows:

TextField(
  maxLength: 100,
  buildCounter: (
    BuildContext context, {
    int currentLength,
    int maxLength,
    bool isFocused,
  }) {
    return Text(
      '$currentLength/$maxLength',
    );
  },
)

Get focus dynamically

FocusScope.of(context).requestFocus(_focusNode);

_FousNode is the focusNode of TextField:

_focusNode = FocusNode();

TextField(
	focusNode: _focusNode,
	...
)

Dynamic Loss of Focus

_focusNode.unfocus();

Text in Transition Color

Builder(
  builder: (BuildContext context) {
    RenderBox box = context.findRenderObject();
    final Shader linearGradient = LinearGradient(
      colors: <Color>[Colors.purple, Colors.blue],
    ).createShader(
        Rect.fromLTWH(0.0, 0.0, box?.size?.width, box?.size?.height));

    return Text(
      'Lao Meng, focus on sharing Flutter Technology and Application Actual Warfare',
      style: new TextStyle(
          fontSize: 18.0,
          fontWeight: FontWeight.bold,
          foreground: Paint()..shader = linearGradient),
    );
  },
)

The Builder component is used to calculate the current Text component size and generate a LinearGradient.

Text with front and rear Tags

RichText(
  text: TextSpan(
      style: DefaultTextStyle.of(context).style,
      children: <InlineSpan>[
        WidgetSpan(
            child: Container(
              margin: EdgeInsets.only(right: 10),
              padding: EdgeInsets.symmetric(horizontal: 10),
              decoration: BoxDecoration(
                  shape: BoxShape.rectangle,
                  borderRadius: BorderRadius.all(Radius.circular(20)),
                  color: Colors.blue),
              child: Text(
                'Judgment Question',
                style: TextStyle(color: Colors.white),
              ),
            )),
        TextSpan(text: 'Foam extinguishers can be used for live fire fighting'),

      ]),
)

"Service Agreement"

Usually at the bottom of the login page, a login appears to represent consent and reading of the Service Agreement, where ** the Service Agreement ** is blue and clickable:

Text.rich(
  TextSpan(
      text: 'Sign in for consent and reading',
      style: TextStyle(fontSize: 11, color: Color(0xFF999999)),
      children: [
        TextSpan(
          text: '<Service Agreement',
          style: TextStyle(color: Colors.blue, fontWeight: FontWeight.bold),
          recognizer: TapGestureRecognizer()
            ..onTap = () {
              print('onTap');
            },
        ),
      ]),
)

Login Password Input Box

TextField(
  decoration: InputDecoration(
    fillColor: Color(0x30cccccc),
    filled: true,
    enabledBorder: OutlineInputBorder(
        borderSide: BorderSide(color: Color(0x00FF0000)),
        borderRadius: BorderRadius.all(Radius.circular(100))),
    hintText: 'Input password',
    focusedBorder: OutlineInputBorder(
        borderSide: BorderSide(color: Color(0x00000000)),
        borderRadius: BorderRadius.all(Radius.circular(100))),

  ),
  textAlign: TextAlign.center,
  obscureText: true,
  onChanged: (value) {

  },
)

Comment Reply

Text.rich(
  TextSpan(
      text: 'Reply',
      style: TextStyle(fontSize: 11, color: Color(0xFF999999)),
      children: [
        TextSpan(
          text: '@Lao Meng:',
          style: TextStyle(color: Colors.blue, fontWeight: FontWeight.bold),
          recognizer: TapGestureRecognizer()
            ..onTap = () {
              print('onTap');
            },
        ),
        TextSpan(
          text: 'Hello, want to know Flutter What is the future?',
        ),
      ]),
)

Communication

Lao Meng Flutter blog address (330 control usages): http://laomengit.com

Welcome to the Flutter Exchange Group (WeChat: laomengit), Focus on Public Number (Lao Meng Flutter):

Tags: Mobile Android iOS

Posted on Wed, 10 Jun 2020 20:27:26 -0400 by LarsLai