Author: Idle fish technology – Artistic conception

Flutter is a new responsive, cross-platform, high-performance mobile development framework. Since open source, it has been loved by more and more developers. Xianyu was one of the first companies to partner with Google and use the service in key product details pages. Along the way, accumulated a lot of development experience. While more and more technical professionals are making a splash in the Flutter world, there are certainly a lot of fluffers out there hoping to get up to speed and enjoy the fun of programming the flutter. This article is for students who are new to Futter to learn about Flutter from one of the most basic concepts in the system. Hope to help every beginner.

Maybe the first question you want to ask is why start with widgets?

From the architecture diagram of Flutter, it is easy to see that the widgets are the basis for the overall view description. The core design idea of Flutter is

Everything 's a WidgetCopy the code

Everything is a Widget. In the World of Flutter, concepts like views, View controllers,layouts, etc., are built on widgets. The widget is an abstract description of the functionality of Flutter. So the basis for mastering Flutter is to start by learning to use widgets.

This article introduces the basics of the Flutter components and layout from a familiar UI drawing perspective. First of all, I listed the most commonly used and basic components in UI development. The following are introduced one by one.

Article 1 components

1.1 the Text

Text is almost one of the most important components in UI development, and the display of Text on the UI is basically done by the Text component. Flutter provides a native Text component. The configuration properties of Text are very rich. The properties are mainly divided into two parts: one is the alignment & display control in the properties of the Text class, and the other is the style related properties which are controlled by the separate class TextStyle. Compared to native controls (take Android as an example), the Text component provides basically the same capabilities and provides richer styling capabilities. Detailed attributes can be found in the official document Flutter Text.

1.1.1 practice Coding

Set text & text size & color & line limit & Text alignment

const Text(  "hello flutter!", textAlign: textalign. center, maxLines: 1, overflow: textoverflow. ellipsis,... Style: TextStyle(fontSize: 30.0,// text-size: color.yellow),// text-color: color.yellow),Copy the code

The effect is as follows:

1.2 the Image

Graphics are also one of the most important components of UI development. Can look at the picture with the text of the era, the picture is the most important page display! Flutter also provides an Image component natively. Here are some key points:

1.2.1 zoom

How to set the zooming of the image? Image scaling in the Flutter is controlled by the FIT field. This is a parameter that has a great impact on the final picture display effect, and is also a point of error. Here’s a look at the scaling options provided by the Flutter Image component.

The value of the zoom property is in the BoxFit enumeration

The images listed below are samples of various scales that flutter officials have done. Basically all the statements are very clear, just sort out for you to refer to.

attribute Scale effects
fill
contain
cover
fitWidth
fitHeight
none
scaleDown

1.2.2 Image acquisition

How to load images from various sources? The default Image component cannot display images directly. It requires an ImageProvider to provide specific Image resources (that is, the Image field in the Image needs to be assigned a value). This may seem cumbersome at first glance, but the ImageProvider does not need to completely reimplement itself. In the Image class currently provides a few good ImageProvider implementation, can basically meet the common needs.

ImageProvider use
Image.asset Get the image from the Asset resource file
Image.network Get pictures from the web
Image.file Get the image from the local file
Image.memory Get the picture from memory

Image also supports GIF images

The network request Image is the most common operation. Here are two key points:

  • The cache

ImageCache is the default ImageCache used by the ImageProvider. ImageCache uses the LRU algorithm. By default, 1000 images can be stored. If the cache is too large, you can control the number of images cached by setting the maximumSize property of ImageCache. The cache size can also be controlled by setting maximumSizeBytes (the default cache size is 10MB).

  • CDN optimization

If you want to use CDN optimization, you can do it by adding a suffix to the URL. This point is not included in the default implementation, but given the considerable benefits of CDN optimization, it is recommended that you take advantage of it.

1.2.3 FadeInImage

In the actual development, considering the image loading speed may not be as expected. So hopefully we can add fade in & add placeHolder functionality. Flutter also provides one such component – FadeInImage.

FadeInImage also provides the ability to load images from multiple sources. This is not so different. I won’t repeat it here.

1. Practice Coding

  • Get images from the Internet and keep them in proportion and as large as possible
new Image.network(
            'https://gw.alicdn.com/tfs/TB1CgtkJeuSBuNjy1XcXXcYjFXa-906-520.png', fit: boxfit.contain, width: 150.0, height: 100.0,),Copy the code
  • The effect is as follows:

1.3 the Container

The idea behind the Flutter is to be completely Widgetten. What that means is that even the basic padding, the Center, is a widget. Imagine if you had to package a component every time you wrote the View, the padding, the Center? As an engineer, don’t just talk to me about ideas, the operational efficiency of the actual operation is also very important. The officials of Flutter are aware of this problem and they have provided a friendly and efficient package from the Angle of actual writing efficiency. This is Container! First of all, not surprisingly, Container itself is a widget. It does, however, provide a wrapper around the base widgets, improving the efficiency of the presentation of the basic UI decoration capabilities. Container is similar to ViewGroup in Android.

I believe that most of the attributes will be very familiar to everyone, combined with the code comments are relatively easy to understand, so I won’t repeat them here. Important to explain are the Decoration and BoxConstraints.

1.3.1 decoration

Decoration is a description of how to decorate a Container. The concept is similar to Shape in Android. The subclass BoxDecoration is usually used in real-world scenarios. BoxDecoration provides customization for background colors, borders, rounded corners, shadows, gradients, and more. A few points to note:

  • The BoxDecoration image property is equivalent to setting the background image. But the image is drawn on top of the color and gradient.
  • Image is an implementation that requires a DecorationImage class. The DecorationImage properties are similar to those of the Image component, and you can reuse the ImageProvider in the Image component.

1.3.2 size

BoxConstraints is actually a description of the size of the Container component. The BoxConstraints property is simpler. Look at the box model if you’re not sure. Here’s an important point to make:

  • How to express this as much as possible? (Similar to Match_parent in Android) The Flutter uses double. Infinity to make a similar expression.

1.3.3 practice Coding

  • Set borders & Padding&Margin & Rounded corners & Background
New Container(alignment: alignment. Center, padding: const edgeinset. all(15.0), margin: Const EdgeInsets. All (15.0), decoration: new BoxDecoration(border: new border. All (color: color.red,), image: const DecorationImage( image: const NetworkImage('https://gw.alicdn.com/tfs/TB1CgtkJeuSBuNjy1XcXXcYjFXa-906-520.png',), fit: boxfit.contain,), //borderRadius: const borderRadius. All (const radius.circular (6.0)), borderRadius: Const BorderRadius. Only (topLeft: const Radius. Circular (3.0), topRight: const Radius. Circular (6.0), bottomLeft: const BorderRadius. BottomRight: const radius.circular (0.0),),), child: Text(const radius.circular (0.0),), child: Text(const radius.circular (0.0),),' '),),Copy the code
  • The effect is as follows:

1.4 Gesture Operation

Gestures are the most common UI interaction. Gesture recognition is also a widget in Flutter! This is something new for new people. Generally, the GestureDetector class is used to handle the click event. When using the GestureDetector, you only need to wrap the GestureDetector around the target widget, and then implement the function of the corresponding event. From clicking to long-pressing, from zooming to dragging, this class basically has an implementation. For details, see the component documentation.

2. Layout

Page layout should be the most fundamental knowledge of UI writing, its main description is the parent component and child components between the location of the relationship. First let’s understand the logic of the official document:

The layout of the Flutter is divided into single and multiple children. This is new for native R & D students. Single child components mainly inherited from SingleChildRenderObjectWidget. These components can provide rich decorative capabilities (such as Container) as well as some specific layout capabilities (such as Center). Many children component inherits from MultiChildRenderObjectWidget, can provide more abundant ability of layout (Flex, Stack, flow), but almost no decoration. Here are some key layouts:

2.1 the Flex

Flutter also provides full Flex layout capabilities on the layout. However, the Layout Widgets in the Official Flutter document do not contain any Flex. I see Row and Column. What the hell is that? It’s not hard to find components like Row and Column whose base class is Flex. The difference between Row and Column is that they have different flex-directions. This is because the Flutter widget was designed with the UI layout semantics in mind from the beginning. This should be partly based on the experience of the front end, trying to avoid the embarrassment of a single div doing the whole page (of course Flutter can do the same thing with Flex, but this is not recommended). The Flex model that Flutter uses is basically similar to traditional Css. This front end students can quickly learn. But Flex is a new way of laying things out for clients. For the basics of Flex, see Flex Layout Basics. Because space is limited, I will not elaborate here. Here’s just one important point: The flex layout concept looks like this:

2.1.1 practice Coding

Ok, after reading this knowledge, let’s actually operate a few cases to get familiar with Flex from the perspective of actual requirements.

  • In the middle
new Flex(direction: Axis.horizontal, mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment center, the children: "Widget > [new Container (width: 40.0, height: 60.0, color: Colors, pink, the child: const Center( child: const Text("left"),)), new Container(width: 80.0, height: 60.0, color: color. grey, Child: const Center(Child: const Text("middle"),)), new Container(width: 60.0, height: 60.0, color: color. yellow, child: const Center(Child: const Text("right"))),]),Copy the code
  • The effect is as follows:

  • Weight left: Right =2:1 Set the Flexible Flex value to complete the ratio setting
new Flex( direction: Axis.horizontal, mainAxisAlignment: MainAxisAlignment.spaceEvenly, crossAxisAlignment: CrossAxisAlignment.center, children: <Widget>[ new Flexible( flex: 2, fit: FlexFit.loose, child: new Container( color: Color. blue, height: 60.0, alignment: alignment. Center, child: const Text(color. blue, height: 60.0, alignment: alignment.'left! ', textAlign: TextAlign.center, style: TextStyle(color: Colors.black), textDirection: TextDirection.ltr), ), ), new Flexible( flex: 1, fit: FlexFit.loose, child: new Container( color: Colors.red, height: 60.0, alignment: alignment. Center, child: const Text(60.0, alignment: alignment.'right',
                   textAlign: TextAlign.center,
                   style: TextStyle(color: Colors.black),
                   textDirection: TextDirection.ltr),
             ),
           ),
         ],
       )
Copy the code
  • The effect is as follows:

2.2 the stack

In real development, you still need to overlay some Widgets on top of others. This is where the layered layout comes in. This layout on Native, android for example, is similar to a relativeLayout or FrameLayout. In Flutter, Stack is used.

In practice, there are two types of child Widgets in the Stack:

  • positioned
    • It’s a module wrapped in a mini-capsule
    • Can be Positioned flexibly through the tourist property
  • non-positioned
    • It’s not wrapped in a c-capsule
    • You need to control the layout through the properties of the parent Widget Stack

For the non-c-children, we control the alignment by controlling the alignment property of the Stack. The arrangement of tourists is similar to the absolute arrangement of the position layout in H5& Weex. By setting the distance from the parent module above, below, left and right, the object will be able to control the display of the view more flexibly in the Stack layout.

2.2.1 practice Coding

  • Cascade layout
New Container(color: color. yellow, height: 150.0, width: 500.0, child: new Stack(children: <Widget>[new Container(color: Colors. BlueAccent, height: 50.0, width: 100.0, alignment: alignment. Center, child: Text('unPositioned'C-21 would offer tourists a small glimpse of space.),), new Container(left: 40.0, top: 80.0, child: new Container(color: Colors. Pink, height: 50.0, width: 95.0, alignment: alignment. Center, child: Text(95.0, alignment: alignment.'Positioned')))))Copy the code
  • The effect is as follows:

3. Visibility

When you read the Flutter Widge documentation, we suddenly find a slightly awkward question: does the component show how to control it? It seems that all components do not have this property! What do we do?

At present, the methods are as follows:

3.1 remove method

The core removes the real widget or widget tree from the renderTree.

Concrete to the practical level, there are mainly two:

  • Individual components’ hide ‘themselves. Return an empty Container in the build method.
@override
Widget build(BuildContext context) {
  returnisVisible ? Widget // True Widget: new Container(); // The empty Widget only occupies the space and is not displayed}Copy the code
  • More than one child

Delete the corresponding cell from the list of the children field of the parent container.

3.2 Offstage

Offstage is a widget. If the Offstage property of the Offstage is set to true, neither the Offstage nor its children will be drawn to the interface. The sample code is as follows:

@override
Widget build(BuildContext context) {
  returnnew Offstage( offstage: ! isVisible, child:child); }Copy the code

3.3 the transparency

Set the transparency of the widget so that it is not visible. But there are side effects. Because the corresponding widget tree has gone through the full layout&paint process, the cost is high. At the same time, setting the transparency itself also consumes some computing resources, resulting in secondary waste. It’s important to note that even when it’s transparent, it still occupies the same position. We choose to use it carefully. The sample code is as follows:

@override
Widget build(BuildContext context) {
  returnnew AnimatedOpacity( duration: Duration(milliseconds: 10), opacity: isVisible ? Child: 1.0:0.0, child); }Copy the code

Visibility control is more troublesome. This is a point in the design of the Flutter that is out of whack and needs your attention.

4 Life Cycle

4.1 State Life cycle

Widgets are immutable and need to be rebuilt when they change, so they are not state. State preservation in StatefulWidget is actually implemented through the State class. State has its own lifecycle, which is briefly described below.

The name of the state
initState Called once when the render tree is inserted
didChangeDependencies Called when the object on which state depends changes
didUpdateWidget Called when a component’s state changes, possibly multiple times
build Called when the Widget is built
deactivate Called when the render tree is removed
dispose Called when the component is about to be destroyed

The life cycle status chart is as follows:

A few points to note

  • DidChangeDependencies is called in two cases.

    • Creation time is called after initState
    • Is called when the dependent InheritedWidget changes
  • A normal exit process deactivate and dispose. However, after deactivate, you can directly join another node in the tree without dispose.

  • There are two possible state changes here: 1. Change by setState content 2. The state status of the parent node changes, resulting in synchronization changes of the child node.

4.2 App Life Cycle

It should be pointed out that if you want to know the App lifecycle, so need to get through WidgetsBindingObserver didChangeAppLifecycleState. The life cycle that can be obtained through this interface is in the AppLifecycleState class. Common states include the following:

The name of the state
resumed Visible and responsive to user input
inactive In inactive state, unable to process user response
paused Invisible does not correspond to user input, but continues in the background

An example from a real world scenario:

Suspending situations without considering: from back to front life cycle changes are as follows:

  • AppLifecycleState.inactive->AppLifecycleState.resumed;

The life cycle changes from foreground to background as follows:

  • AppLifecycleState.inactive->AppLifecycleState.paused;

5 Beginner’s confusion

5.1 Why use dart language?

Dart is a new language to most developers. Why did Google choose such an unpopular language to develop Flutter? The main reasons are as follows:

    1. Dart has jit&Aot dual compilation execution. In this way, JIt can be used for hot Reload development during the development phase, improving the r&d efficiency. Aot is also used in the final release to translate the DART code directly into the instruction set code for the target platform. Simple and efficient to maximize performance.
    1. Dart optimizes GC specifically for scenarios in which destruction widgets are frequently created in flutter. Minimize the impact of GC on performance by generalizing lockless garbage collectors.
    1. Dart is java-like in syntax and is easy to learn and use.

5.2 Why Are Widgets immutable?

In my opinion, there are two main points:

  • The core idea of Flutte in page rendering is that simple is fast! Widgets are designed to be immutable, so Flutter chooses to rebuild the widget tree to update the data when the data changes. The advantage of this approach is that the framework does not need to worry about the scope of the data impact, so it is simple and efficient. The disadvantage is that it stresses the GC.
  • Reuse of component descriptions Since widgets are immutable. That widget can be reused at a lower cost. It is possible to have different nodes in the same widget rendering tree in a real rendering tree.

5.3 Is a Widget a View?

Perhaps one of the most puzzling questions for those who are new to Flutter is the relationship between widgets and views. Here’s a quick breakdown: A widget is a description of a page’s UI. Its function classes are a bit like XML on Android, or HTML on the Web. Widgets are converted to Elements when rendered. An Element adds context information compared to a Widget. An Element is an instantiated node that corresponds to the Widget in the render tree. Because widgets are immutable, the same widget can simultaneously describe nodes in more than one render tree. But an Element is a description of a point fixed at a particular location in the render book. In short, widgets are reusable as a description, but elements correspond to the nodes that need to be drawn. Is element the final rendered view? Sorry, not yet. Element is converted to rendObject when drawn. RendObject is the object that actually goes through layout and paint and is drawn on the screen. There are three sets of render related trees in Flutter: Widget Tree, Element Tree & rendObject Tree. The rendering process of the three is as follows:

So one might ask, why do you need to add an Element tree in the middle?

  • 1. No need to directly manipulate the UI, instead go through a data-driven view. Code expression can be more refined.
  • 2. The maximum level reduces the modification of the final real view (rendObject tree) and improves the rendering efficiency of the page.

5.4 Differences between StatelessWidget and StatefulWidget

A StatelessWidget is a widget whose state is immutable. After the initial state is set, it cannot be changed. If you need to change you need to re-create. StatefulWidget can save its state. So the question is, since widgets are immutable, how do we store state? The idea behind Flutter is to preserve State by introducing State. When the State of State changes, you can rebuild this node and your child’s Widget tree to make UI changes. Note: If you need to actively change the State, you need to trigger the setState() method. Simply changing the data will not cause the UI to change.

6. Contact us

This article explains the basic components in detail and also answers some beginner’s questions. I hope to give some help to those who just set foot on the road of learning flutter. If you have any questions or corrections about the text, please let us know.

Xianyu technical team is a short and concise engineering and technical team. We not only focus on the effective solution of business problems, but also push the cutting edge practice of breaking the constraints of the technology stack (the unification of android/iOS/Html5/Server programming model and language), computer vision technology on mobile terminals. As a software engineer in the Xianyu Technical team, you have the opportunity to demonstrate all of your talents and courage in the evolution of the entire product and user problem solving to prove that technology development is a power to change the way of life. Resume delivery: [email protected]

7. References:

  • 1. Flutter. IO/widgets – int…
  • 2. Flutter. IO/technical – o…
  • 3. Introduction to the CSS box model
  • 4. The flutter Layout Widgets directory
  • Flex Layout basics
  • 6.A Visual Guide to CSS3 Flexbox Properties
  • 7. Why is Flutter revolutionary?
  • 8. Learn more about the Development of the Flutter interface