Flutter's text, picture and button usage

Knowledge such as the view data flow mechanism, the underlying rendering scheme, and the view update strategy are the foundation of a UI framework. It may seem boring, but it often has the longest vitality.

Therefore, only by understanding these most basic knowledge and improving internal skills can we comprehend by analogy, form our own knowledge system from point to surface, and think about the rationality of application layer construction view implementation on top of the framework.

After you have an overall impression of the basic view, learn the UI controls provided by the Flutter view system. As a UI framework, similar to Android, iOS and React, Flutter also provides many UI controls. Text, pictures, and buttons are the most basic controls used to build views in these different UI frameworks.

1 text control

Text is a common control in the view system, which is used to display a string of a specific style, such as TextView in Android and UILabel in iOS. In Flutter, text display is realized through the Text control.

Text supports two types of text display:

  • The default display of a single style of text Text
  • Rich text Text.rich that supports multiple mixed styles

1.1 Use a single style of text Text

The initialization of the single-style text Text needs to pass in the string to be displayed. The specific display effect of this string is controlled by other parameters of the constructor. These parameters are divided into:

  • Parameters that control the overall text layout , such as text alignment textAlign, text layout direction textDirection, text display maximum number of lines maxLines, text truncation rule overflow, etc. are all parameters in the constructor
  • Parameters that control the text display style , such as font name fontFamily, font size fontSize, text color color, text shadow shadows, etc., these parameters are uniformly encapsulated into the parameter style in the constructor

Display a single style of text Text

Centered layout, 20 red bold display style strings:

Text(
  '文本是视图系统中的常见控件,用来显示一段特定样式的字符串,就比如Android里的TextView,或是iOS中的UILabel。',
  textAlign: TextAlign.center,//居中显示
  style: TextStyle(fontWeight: FontWeight.bold, fontSize: 20, color: Colors.red),//20号红色粗体展示
);

The running effect is shown in the figure below:

Figure 1: Example of single-style text Text

Support multiple mixed display styles in a string

The key difference from a single style is fragmentation, that is, how to divide a string into several fragments, and set styles for each fragment separately:

  • Android uses SpannableString to achieve
  • Use NSAttributedString in iOS to achieve
  • Flutter also has a similar concept TextSpan

TextSpan defines how a string segment should control its display style, and assembling these strings with independent display styles can support mixed-style rich text display.

Define two display styles of black and red respectively, then divide a string into 4 fragments, and set different display styles:

TextStyle blackStyle = TextStyle(fontWeight: FontWeight.normal, fontSize: 20, color: Colors.black); //黑色样式

TextStyle redStyle = TextStyle(fontWeight: FontWeight.bold, fontSize: 20, color: Colors.red); //红色样式

Text.rich(
    TextSpan(
        children: <TextSpan>[
          TextSpan(text:'文本是视图系统中常见的控件,它用来显示一段特定样式的字符串,类似', style: redStyle), //第1个片段,红色样式
          TextSpan(text:'Android', style: blackStyle), //第1个片段,黑色样式
          TextSpan(text:'中的', style:redStyle), //第1个片段,红色样式
          TextSpan(text:'TextView', style: blackStyle) //第1个片段,黑色样式
        ]),
  textAlign: TextAlign.center,
);

The running effect is shown in the figure below:

Figure 2: Mixed style rich text Text.rich example

Look at the image control Image in Flutter.

2 pictures

Using Image allows us to display an image to the user. There are many ways to display pictures, such as resource pictures, network pictures, file pictures, etc., and the picture formats are different. There are also many ways to load different forms and support pictures in different formats in Flutter:

  • Load local resource images, such as Image.asset('images/logo.png')
  • Load local (File file) images, such as Image.file(new File('/storage/xxx/xxx/test.jpg'))
  • Load network images, such as Image.network( 'http://xxx/xxx/test.gif')

In addition to setting different image sources according to the image display method, the image construction method also provides:

  • fill mode fit
  • stretch mode centerSlice
  • Repeat mode repeat and other attributes

The layout mode can be formulated according to the aspect ratio difference between the picture and the target area.

This is similar to the properties of ImageView in Android and UIImageView in iOS. You can refer to the Image Constructor section in the official documentation to see how to use the Image control.

FadeInImageControl

Loading network images, in order to improve the user's waiting experience, elements such as placeholder images and loading animations will be added, but the default Image.network construction method does not support these advanced functions, so the FadeInImage control is useful.

The FadeInImage control provides the image placeholder function and supports the visual effect of fading in and out when the image is loaded. Since Image supports gif format, some cool loading animations can also be used as placeholders.

When loading a large image, display a loading gif as a placeholder image to the user:

FadeInImage.assetNetwork(
  placeholder: 'assets/loading.gif', //gif占位
  image: 'https://xxx/xxx/xxx.jpg',
  fit: BoxFit.cover, //图片拉伸模式
  width: 200,
  height: 200,
)
Figure 3: FadeInImage placeholder

The Image control needs to determine the display effect according to the asynchronous loading of image resources, so it is a StatefulWidget. The image loading process is triggered by ImageProvider, and ImageProvider represents the operation of asynchronously obtaining image data, which can obtain images from different channels such as resources, files, and networks.

  • ImageProvider generates the corresponding image cache key according to the image configuration passed in _ImageState
  • Then go to ImageCache to find out whether there is a corresponding image cache:
    • Yes, notify _ImageState to refresh the UI
    • No, start ImageStream to start asynchronous loading, after loading, update the cache
  • Finally, notify _ImageState to refresh the UI

Picture display process:

Figure 4: Image loading process

ImageCache uses the LRU cache update strategy. By default, it can store up to 1000 pictures, and the maximum cache limit is 100MB. When the limited space is full of data, the pictures that have not been accessed for the longest time will be cleared. The image cache will only take effect during runtime, that is, it will only be cached in memory . To support caching to the file system, use the CachedNetworkImage control.

CachedNetworkImage is similar to Image. In addition to supporting image caching, it also provides more powerful loading process occupancy and loading error occupancy than FadeInImage, and supports custom control occupancy that is more flexible than image occupancy.

When loading an image, not only will the user be shown the space-occupied rotating circle loading, but an error map will also be provided in case the image loads incorrectly:

CachedNetworkImage(
        imageUrl: "http://xxx/xxx/jpg",
        placeholder: (context, url) => CircularProgressIndicator(),
        errorWidget: (context, url, error) => Icon(Icons.error),
     )

3 buttons

Can respond to user interaction events. Flutter provides three basic button controls:

  • FloatingActionButton: A round button, usually in front of the screen content, which handles the most common and basic user actions in the interface. The "+" floating button of the counter example is the FloatingActionButton
  • RaisedButton: A raised button with a gray background by default, and the gray background will deepen after being clicked
  • FlatButton: A flat button with a transparent background by default and a gray background when clicked

The only difference in how to use the button control is the default style.

Define FloatingActionButton, FlatButton and RaisedButton respectively, the functions are exactly the same, and the text will be printed when clicked:

FloatingActionButton(onPressed: () => print('FloatingActionButton pressed'),child: Text('Btn'),);
FlatButton(onPressed: () => print('FlatButton pressed'),child: Text('Btn'),);
RaisedButton(onPressed: () => print('RaisedButton pressed'),child: Text('Btn'),);

Button control:

image-20230623145628607

Since it is a button, in addition to controlling the basic style, it also needs to respond to the user's click behavior. This corresponds to the two most important parameters in the button control:

  • The onPressed parameter is used to set the click callback, telling Flutter to notify us when the button is clicked. If the onPressed parameter is empty, the button will be disabled and will not respond to user clicks
  • The child parameter is used to set the button content, tell Flutter what the control should look like, that is, control the basic style of the button control. Child can receive any Widget, such as the Text passed in in the above example, and controls such as Image can also be passed in

Although the basic style of the button control can be controlled through the child parameter, the default style of the system is too monotonous, and the control style is usually customized. Similar to the Text control, the Button control also provides rich style customization functions, such as background color color, button shape shape, theme color colorBrightness, etc.

Take FlatButton as an example to introduce button style customization:

FlatButton(
    color: Colors.yellow, //设置背景色为黄色
    shape:BeveledRectangleBorder(borderRadius: BorderRadius.circular(20.0)), //设置斜角矩形边框
    colorBrightness: Brightness.light, //确保文字按钮为深色
    onPressed: () => print('FlatButton pressed'),
    child: Row(children: <Widget>[Icon(Icons.add), Text("Add")],)
)

Combine a plus icon with text to define the basic appearance of the button; then specify its shape as a beveled rectangular border through shape, and set the background color of the button to yellow.

Because the background color of the button is light, in order to prevent the button text from being read clearly, we set the button theme colorBrightness to Brightness.light to ensure that the button text color is dark. Display of results:

Figure 6: Button Control Custom Appearance

4 Summary

UI controls are the basic elements for building a view, and text, pictures and buttons are the most classic controls.

First of all, recognize the text display control Text that supports two types of single style and mixed style:

  • The display style of the string is controlled by TextStyle, and other parameters control the text layout to achieve a single style of text display
  • Divide the string into several fragments through TextSpan, set the style for each fragment separately and then assemble it to support mixed-style rich text display

An image control Image that supports multiple image source loading methods. Image internally uses ImageProvider to trigger the asynchronous loading process according to the cache status, and notify _ImageState to refresh the UI. However, since the image cache is a memory cache, it only takes effect during runtime. To support caching to the file system, use a CachedNetworkImage.

Finally learn the button control. Flutter provides a variety of button controls, which are used in a similar way. The child parameter of the control initialization is used to set what the button looks like, and the onPressed parameter is used to set the click callback. Similar to Text, there is also a rich UI customization interface inside the button.

UI basic information expression, there is no essential difference between the Flutter classic controls and the controls provided by the native Android and iOS systems. But custom control styles, these classic controls of Flutter provide powerful and concise expansion capabilities, and quickly develop pages with complex functions and rich styles.

5 FAQ

Read the source code of Text, Image, FadeInImage, and button controls FloatingActionButton, FlatButton, and RaisedButton in the Flutter SDK, and find out the controls that actually carry their visual functions internally in the build function. What did you find?

When reading the source code of Text, Image, FadeInImage, FloatingActionButton, FlatButton, and RaisedButton in the Flutter SDK, you can find that their build functions have a control that actually carries their visual functions.

  • For the Text control, the control that actually carries its visual function inside is RichText.
  • For the Image control, the control that actually carries its visual function is RawImage.
  • For the FadeInImage control, the controls that actually carry its visual functions are AnimatedOpacity and RawImage.
  • For the FloatingActionButton control, the internal controls that actually carry its visual functions are Material and InkResponse.
  • For the FlatButton control, the internal controls that actually carry its visual functions are Material and InkWell.
  • For the RaisedButton control, the internal controls that actually carry its visual functions are Material and InkResponse.

These controls are the basic controls provided in the Flutter framework and are used to achieve various visual effects. In the build function of these controls, these basic controls will be created according to different attribute values ​​and combined to achieve the desired visual effect.

Then share some Java interview-related materials I compiled and summarized (personally verified, rigorous and scientific! Don’t read the misleading garbage interview questions on the Internet!!!), to help you get more offers!

Click to get more classic must-read e-books!

The latest Java learning route in 2023 is one-stop:

Let me recommend a public account [JavaEdge] for learning Java and preparing for Java interviews (strongly recommended!)

Guess you like

Origin blog.csdn.net/qq_33589510/article/details/131351330