The idea behind Flutter is that everything is a “Widget”. Widgets are the components we use for development. Developers use them for page development, UI display, action interaction, and so on.
The Widget overview
Flutter widgets can be divided into three main categories: composite, rendered, and proxy. Composite widgets are common statelessWidgets and statefulWidgets. Renderings are mostly system-provided components that can be used directly, such as Padding, RichText, etc. Proxy is providing proxy functionality for child nodes, such as inheritedWidgets, and so on.
StatelessWidget
Statelesswidgets are stateless components, and the SDK version 2.2 provides about 109 of them. The diagram below:
The image is so large that you can view it by clicking on it. The commonly used components include Container, ListView, Visibility, SafeArea, and so on.
StatefulWidget
Statefulwidgets are state components, and the 2.2 SDK provides 170+ of these types of components, as shown below:
It’s a long picture, so you can click on it. Common components of this type include WillPopScope for fallback interception, TextField for input boxes, Overlay of floating window components, Scaffold for page containers, and so on.
RenderObjectWidget
RenderObjectWidget is a render type component that provides an object for rendering.
Common components of this type are Row and Column for elastic layouts, Padding for spacing, SizedBox for layout constraints, List for the Sliver family, and so on.
ProxyWidget
ProxyWidget is a proxy component and does not participate in drawing. There are relatively few widgets of this type in Flutter.
The most common components of this type are theme-specific, configuration-specific, etc., such as size-specific MediaQuery, theme-specific SliderTheme, configuration-specific KeepAlive, and so on.
summary
The above is an overview of the widgets, many of which are confusing to see 🙄. In our daily development, we might use just a few: Scaffold, Omnibus Container, Horizontal layout Row, vertical layout Column, Flow layout Wrap, Cascading layout Stack, list scroll ListView, grid scroll GridView, nested slide CustomScrollView, single scroll Sing LeChildScrollView, GestureDetector, graphic components, ValueListenableBuilder for state management, and more.
These fall into roughly five categories: graphic components, container components, layout components, scroll components, and functional components. Let’s take a look at the details in turn.
Graphic components
As the name implies, the graphic component is to display Text and pictures. The commonly used controls are: plain Text Text, RichText RichText, simple picture Image, and excessive effect FadeInImage.
Plain Text Text
A run of text with a single style. Displays a single styled text component.
attribute | type | role |
---|---|---|
data | String | Mandatory: Indicates the text to be displayed. |
key | Key? | Components of the key |
style | TextStyle? | The Style of the text display, the font color, the text background color and foreground color, the text size, the weight of the font, etc., and all the attributes related to the text display are in the Style. |
strutStyle | StrutStyle? | It relates to the baseline of the text |
textAlign | TextAlign? | Alignment of text |
textDirection | TextDirection? | The direction of the text is left to right or right to left |
locale | Locale? | Identifiers for language and format preferences. |
softWrap | Bool? | Whether text breaks on line breaks |
overflow | TextOverflow? | The effect of text overflow |
textScaleFactor | double? | The scale factor of the text |
maxLines | int? | The maximum number of lines of text |
semanticsLabel | String? | Semantic labels for text (accessibility) |
textWidthBasis | TextWidthBasis? | A method of measuring words |
textHeightBehavior | TextHeightBehavior? | Handles the height above and below the text |
Now let’s look at the actual chestnut
class _TextTestPageState extends State<TextTestPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Text component'),
),
body: Center(child: Text('Text Text component demo '))); }}Copy the code
In the middle of the screen is the simplest text component, which looks like this:
To change the text color, font, and so on, add the TextStyle attribute
Except for simple size, weight and color. TextStyle also allows you to modify text spacing, text background color, text decoration, and more.
The letterSpacing property is the spacing between individual letters or Chinese characters, and wordSpacing is the spacing between words, which are two parts separated by Spaces.
As you can clearly see from the figure above, there is spacing between characters.
You can see that the gap between the words has widened.
In addition to the simple backgroundColor, you can also use a background of the type Paint as the text background.
Instead of setting the entire text’s background to a color, use Paint to support borders, anti-aliasing, and so on, with a black border. 🧐 Note that the overall line height of English letters is lower due to differences between Chinese and English.
In addition to the above Text style modifications, Text has some modifications that handle the Text component.
For example, maxLine is the maximum number of lines, and overflow deals with overflow effects of text.
enum TextOverflow {
/// Direct truncation
clip,
/// Words fade
fade,
/// At the end... show
ellipsis,
/// Beyond parts are still rendered although invisible
visible,
}
Copy the code
This is the control of line count and overflow effects. Note here that textoverflow. fade needs to be used in conjunction with the softWrap property, which will fade away when softWrap is set to false. The drawback is that only one line can be displayed.
These are some of the properties commonly used by plain text components.
The rich text RichText
Text is a simple Text component, RichText can be implemented through RichText.
attribute | type | role |
---|---|---|
text | InlineSpan | Mandatory, rich text content to be displayed |
key | Key? | Components of the key |
strutStyle | StrutStyle? | It relates to the baseline of the text |
textAlign | TextAlign? | Alignment of text |
textDirection | TextDirection? | The direction of the text is left to right or right to left |
locale | Locale? | Identifiers for language and format preferences. |
softWrap | Bool? | Whether text breaks on line breaks |
overflow | TextOverflow? | The effect of text overflow |
textScaleFactor | double? | The scale factor of the text |
maxLines | int? | The maximum number of lines of text |
textWidthBasis | TextWidthBasis? | A method of measuring words |
textHeightBehavior | TextHeightBehavior? | Handles the height above and below the text |
With the exception of text, the other attributes work the same as text. InlineSpan has two subclasses: TextSpan for displaying text and WidgetSpan for displaying custom widgets.
TextSpan:
String? Text Displays the text content. List? TextStyle? Style span text style GestureRecognizer? Recognizer text gesture event MouseCursor? MouseCursor The cursor with the finger or mouse hovering over a span
WidgetSpan:
Widget Child Widget UI displayed.PlaceholderAlignment Alignment of the widgets TextBaseline? Baseline Widget Text Baseline TextStyle? The text style of the Style widget
In addition to the differences in display content, TextSpan also supports the concatenation of spans, and WidgetSpan is the end point.
The code above looks like this:
RichText(
text: TextSpan(
text: "Fragments of gray.",
style: TextStyle(color: Colors.black12, fontSize: 16),
children: <InlineSpan>[
TextSpan(
text: 'Red clickable snippet', recognizer: TapGestureRecognizer() .. onTap = () {print('onTap');
},
style: TextStyle(color: Colors.red, fontSize: 16),
),
WidgetSpan(child: Icon(Icons.ac_unit))
]),
)
Copy the code
Recognizer recognizer has gestures like long presses in addition to click gestures, and RichText implements parsing CSS, XML and other tool components.
Image component Image
The simplest Image presentation component is the Image.
attribute | type | role |
---|---|---|
key | Key? | Components of the Key |
image | ImageProvider | Image components display content, network, files, assets, memory, etc |
frameBuilder | ImageFrameBuilder? | Construct a Widget that represents an Image. You typically use this property to add an Image effect such as fade in or placeholder |
loadingBuilder | ImageLoadingBuilder? | The image clip in builder shows the Widget during loading |
errorBuilder | ImageErrorWidgetBuilder? | Image loading failure display Widget |
semanticLabel | String? | Auxiliary semantics for picture controls |
excludeFromSemantics | bool | Whether to exclude auxiliary semantics |
width | double? | The width of the image space |
height | double? | Height of image space |
color | Color? | Color of the picture |
colorBlendMode | BlendMode? | Image blending modeJuejin. Cn/post / 684490… |
fit | BoxFit? | Image zoom, adaptive and other parameters |
alignment | AlignmentGeometry | The alignment of images within a control |
repeat | ImageRepeat | The way an image is repeated within a control |
centerSlice | Rect? | .9 Area of the picture |
matchTextDirection | bool | Whether to draw along TextDirection |
gaplessPlayback | bool | Whether to show old images |
isAntiAlias | bool | Whether anti-aliasing is used to draw the image. |
filterQuality | FilterQuality | Image quality |
These are the basic properties of the image. We usually display images using the specified naming construct.
[Image], for obtaining an image from an [ImageProvider]. Specify the ImageProvider that displays the image itself
[Image.asset], for obtaining an image from an [AssetBundle]using a key. Load the asset image from the AssetBundle
[Image.network], for obtaining an image from a URL. Load images from the network
[Image.file], for obtaining an image from a [File]. Loads images from the file system
[Image.memory], for obtaining an image from a [Uint8List]. Load images from memory
The following uses network images as an example to view the meanings of attributes.
class _ImageTestPageState extends State<ImageTestPage> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Image components'),
),
body: Image.network(
'https://flutterchina.club/images/homepage/header-illustration.png',),); }}Copy the code
The display effect is as follows:
We can set the width by height and width
Effects such as fading can be achieved by using a frameBuilder. The meanings of a frameBuilder are as follows:
If the property is null, the widget will be drawn whenever the Image is available. This property is commonly used to add an image effect such as fade in or placeholder. Finer control can be achieved with loadingBuilder. If the loadingBuilder is not null, the two properties are chained. The result of the frame is passed to the loadingBuilder.Copy the code
The method is signed as follows:
typedef ImageFrameBuilder = Widget Function(
BuildContext context,
Widget child,
int? frame,
bool wasSynchronouslyLoaded,
)
Copy the code
Context: Is the context. Child: is the image component and is guaranteed to be non-empty. This allows us to wrap the original image component, such as wrapping an animation effect, etc. Frame: Represents the drawing frame of the current picture. Null indicates that the picture has not been drawn yet. WasSynchronouslyLoaded: Indicates whether the image has been loaded, if false, then the image is not yet drawable
LoadingBuilder can be used to achieve the effect of loading, loadingBuilder meaning is as follows:
If the Widget displayed during loading is set to NULL, the image is incrementally loaded and the user does not receive the loading process.Copy the code
The method is signed as follows:
typedef ImageLoadingBuilder = Widget Function(
BuildContext context,
Widget child,
ImageChunkEvent? loadingProgress,
);
Copy the code
The context is the image component, and the child is guaranteed to be non-empty. If the frameBuilder is not empty, the result is passed in. LoadingProgress: represents the current loading phase, where cumulativeBytesLoaded is the number of bytes that have been loaded and expectedTotalBytes is the total number of bytes
We can use color to set the color of the image. The setting rule here is to set the color of the image pixels to the set color.
With this property we can set different channel colors for the same Icon.
Images can also be scaled and repeated, namely the scale and repeat properties.
The scale property is similar to what we call x’s, such as 1x, 2x, 3x. 3X means that there are 9 image pixels for each logical pixel, which means that the image is 3 times as wide as it is actually drawn.
Without limiting the size of the picture, the scope of the picture control is its own size. For example, a 200*200 actual pixel image, our scale is 2, the image control occupies the size of 200*200. But the size of the drawing is 100 by 100. That leaves a lot of white space. The repeat property defines how to fill the empty space.
Repeat, x, y axis fill
RepeatX, fill only in x axis
RepeatY, fill only in the y axis
NoRepeat, don’t fill
In addition to using repetition to fill the space, you can also stretch to fill the remaining space, which is the FIT property. The effect is as follows:
Contain: contain as much as possible | Cover: As small as possible | Fill: stretch to scale |
---|---|---|
FitHeight: Keep the original scale, stretch height | FitWidth: Keep the original scale and stretch the width | None: normal display |
ScaleDown: center display, scaleDown if large |
Placeholder component FadeInImage
The Image component provides the basic display of your Image, and the FadeInImage component provides the ability to display a placeholder map while loading.
attribute | type | role |
---|---|---|
key | Key? | Components of the Key |
image | ImageProvider | Image components display content, network, files, assets, memory, etc |
placeholder | ImageProvide | Placeholder picture provider |
placeholderErrorBuilder | ImageErrorWidgetBuilder? | Placeholder map loading error |
imageErrorBuilder | ImageErrorWidgetBuilder? | Image loading failure display Widget |
bundle | AssetBundle? | Source of the picture |
placeholderScale | double? | The scaling factor of a placeholder image |
imageScale | double? | The scale factor of the image |
excludeFromSemantics | bool | Whether to exclude auxiliary semantics |
imageSemanticLabel | String? | Auxiliary semantics of space |
fadeOutDuration | Duration | The fade time of a placeholder image |
fadeOutCurve | Curve | The fade effect of a placeholder image |
fadeInDuration | Duration | The fade time of the image to be displayed |
fadeInCurve | Curve | The fade effect of the image to be shown |
width | double? | Width of picture |
height | double? | Height of picture |
fit | BoxFit? | Image stretching effect |
alignment | AlignmentGeometry | The alignment of images |
repeat | ImageRepeat | The way images are repeated |
matchTextDirection | bool | Is it consistent with the direction of the text |
placeholderCacheWidth | int? | Width used for booth map codec |
placeholderCacheHeight | int? | Height for booth map codec |
imageCacheWidth | int? | Width used for picture codec |
imageCacheHeight | int? | Height used for picture codec |
Most of the above attributes are similar to images, with most of them related to placeholder maps. As you can see from placeholder, booth maps can come from anywhere: networks, files, etc.
Like Image, FadeInImage also provides named constructs to help us quickly implement components from different sources.
The fadeInImage. assetNetwork placeholder is from the Asset directory and the image is the network diagram.
FadeInImage. MemoryNetwork placeholder figure from memory, image is the network diagram.
The simplest effect is as follows:
We can use the Builder in parameters to achieve more effects, such as displaying a text if the booth map is wrong. We miswrote the path to the placeholder map.
In the same way, imageErrorBuilder can implement images to load and widgets to display when errors occur. We wrote the network path wrong.
conclusion
From the overview of widgets, we can see that there are about 300 or 400 🙄 widgets. We generally use five categories: graphic components, container components, layout components, scroll components, and functional components. This paper introduces some basic usage of graphic component. The basic usage of the remaining type components is explained later in this section.