No surprise, you can also ignore the front-end flutter persuasion guide

Time:2021-2-26

preface

It’s 9012 years. I don’t need to say more about the popularity of flutter. The promotion of flutter video tutorial on Nuggets home page for a long time is enough to prove it.

So just as you have to “get started” before you can “go out”, you have to understand flutter before the front-end persuades flutter.

In this paper, the front-end point of view to give you a smooth: in the eyes of the front-end, what is the difference between the development of flutter?

… and then dissuade=_ =。 [if you want to be dissuaded directly, please slide to the end]

What is flutter

First of all, what is flutter?

Explanation on the official website:

Flutter is an open source SDK of Google, which can build high-performance applications for mobile, web and desktop across platforms.

Of course, of course, although the web side and desktop side can be developed, we will develop moreThis paper focuses on the cross platform development function of flutter.

Well, before flutter, there were actually many cross platform development frameworks, some of which were well-knownC’s xamarin, JS’s native script, Ali’s weex and react native are familiar to all of usThen the less famous ones are even more
No surprise, you can also ignore the front-end flutter persuasion guide

So, why does flutter stand out in a bunch of cross platform development frameworks?

Why flutter?

No surprise, you can also ignore the front-end flutter persuasion guide

  1. Low input and high output
    A set of code, directly produce Android + IOS two platform applications. This is the common advantage of cross platform development framework.
  2. Efficient development
    Through the JIT (just in time) real-time compilation function of flutter, it can provide the hot reload function and quickly develop applications. The front-end students should have a deep understanding of whether the development efficiency of hot reload is high or low.
  3. Rich and elegant UI
    The framework itself provides two kinds of UI components of material design and Cupertino, which are not limited to the OEM of the system itself.
  4. High performance applications
    Same performance as native. The AOT of flutter compiles the code into arm binary, uses its own skia, has no bridge dependency, and can directly access the underlying services of the system. These can make the performance of flutter equal to that of native applications.

What is the most important thing?

Flutter has a good dad!

Let’s think about it. The three main front-end frameworks are react and react native from Facebook and angular from Google. Only Vue has no big company background. In fact, many open source frameworks in the community are actually hatched by large enterprises.

There is a good dad, backed by Google dad, born with a golden key, whose future is immeasurable. The stability and growth of the framework can be guaranteed to give the open source community confidence.

That’s what it’s like to fight dad for a while and fight all the time.

To get back to the point, it is mentioned here that flutter can not be limited to system OEM, and provide better performance than other cross platform frameworks. So why is flutter so good? We can explore it from the framework of flutter.

Flutter frame structure

The frame structure of flutter is as follows:
No surprise, you can also ignore the front-end flutter persuasion guide

Well, I believe you have seen this picture more than once. Understand may have been clear in the chest, do not understand or a face may be muddled force.

Let’s talk about it briefly

From the top down,
The first is the framework, which is written in dart language from top to bottom,

  1. There are encapsulated UI components material and Cupertino [equivalent to front-end UI frameworks such as ant design / element / iView]
  2. The packaged UI components material and Cupertino are assembled from more basic widget components. [the widget here is equivalent to the front-end HTML, div, H1, span and other tag elements]
  3. Next, the widget layer is composed of animation, painting and gesture through rendering. [this is slightly different from the front-end UI. The structure (HTML), style (CSS) and event interaction (JS) of the front-end UI are separated, while in the flutter, they are all widgets]

The framework is engine, and the UI interaction in the framework is rendered by engine. In the engine layer, UI components are drawn through skia graphics engine,SkiaIt is Google’s open source 2D graphics engine, suitable for multiple platform systems, which is also one of the core elements of the cross platform ability of flutter. That’s why we said that flutter canNot limited to OEM components of the system
In other words, if you want to encapsulate an ant design style fluent UI framework, you can build your own UI framework directly through the basic widget. If the underlying UI doesn’t meet your needs. You can directly use dart to call the API of skia image engine and draw your own UI without any restrictions.

Finally, embedded layer, which deals with platform differences, enables the application of flutter to be embedded in various system platforms.

We can see that instead of using OEM on the native system, flutter uses the 2d rendering engine skii to directly render the UI, which makes its platform related layer very low. The platform only provides a canvas, and all the remaining rendering related logic is inside flutter, which makes it have good cross end consistency.

The above is the structure of cross platform development of flutter, so what are the advantages of this design? We can compare the architecture of other application development.

Cross platform architecture comparison

Native

First of all, let’s take a look at the architecture design of native app development. Generally, an app is divided into two parts: UI rendering and system service invocation. What we often call cross platform development is actually cross platform development.

No surprise, you can also ignore the front-end flutter persuasion guide
The UI of native app will be realized through native OEM controls provided by the platform,

The system service call, such as the use of cameras, Bluetooth and other sensors, will also be realized through the API provided by the platform system

This will lead to a problem. The OEM control and system service call specifications and programming languages of different platforms are not unified. Android uses Java / kotlin, while IOS uses Objective-C / swift, which leads to platform differences.

If an app needs to develop several sets of code, the UI effect may not be consistent, which is time-consuming and laborious.

Therefore, there is a need for cross platform development.

Let’s look at common cross platform architectures

Webview

No surprise, you can also ignore the front-end flutter persuasion guide

First of all, the most common cross platform solution is to use WebView directly, which is actually what we often call a hybrid app.

Although the WebView kernel of different platforms is not necessarily the same, it will always follow the W3C specification, so our front-end code can run on the WebView of the platform to realize cross platform development on the UI

As for system service call, we call native methods through bridge and protocol.

The disadvantages of hybrid app are also obvious,WebView is not as good as native

In order to solve the performance problem of WebView, the community has launched another solution

React Native / Weex

No surprise, you can also ignore the front-end flutter persuasion guide
As shown in the figure, react native, weex and other frameworks use the front-end language to describe the cross platform implementation of systems such as OEM. In short, they configure the page layout by writing JS, and then parse it into native controls by react native.

In this way, the performance is obviously improved,Because in essence, rendering is still a native control.

However, even if the performance is improved, it still can not reach the native level, because RN parses the jsbunder file layout through jscore, which is a little bit different from the native direct layout.

In addition, using react native can’t avoid writing native code. If you encounter some complex problems related to the platform, you still have to go deep into the native library to make necessary adjustments. Last year, airbnb gave up RN for similar reasons.

So, can you avoid this problem with flutter? Let’s look at the architecture of the flitter

Flutter

No surprise, you can also ignore the front-end flutter persuasion guide

As I said before, the UI rendering of flutter is based on the image engine of skii, which does not rely on any system platform. The platform only provides a canvas for rendering images on the canvas.

As like as two peas, the rendering mechanism is directly rendered across the original rendering mechanism, rendering the view from its rendering engine.There is no middleman to make a difference.

The rendering performance of the two is also improved for the comparison between their rendering engines.

So far, we have compared several cross platform UI rendering implementations,

What about system service invocation? Flutter does not eliminate the problem of cross platform system service invocation, because the differences in hardware design and programming languages exist objectively and cannot be avoided.

But different from the previous methods of using bridge to call system services, flutter calls system services in the form of platform channel. Skip here first. The communication mechanism here will be described in detail in the following chapters

Web VS Flutter

development language

No surprise, you can also ignore the front-end flutter persuasion guide

Unlike the web, which divides a page into HTML, CSS and JS, everything in flutter is a widget
The specific types of widgets are as follows:

  • Element widget. Such as button, menu, list
  • Style widget. Such as font, color
  • Layout widget. Such as padding, margin

All the widgets are nested together to form a flitter app.

UI syntax

basic style

We are familiar with style syntax and front-end code. We can quickly implement a simple UI with HTML and CSS.

Let’s take a look at a basic box model

<div class="greybox">
    Lorem ipsum
</div>
<style>
.greybox {
  background-color: #e0e0e0; /* grey 300 */
  width: 320px;
  height: 240px;
  font: 900 24px Georgia;
}
</style>
var container = Container( // grey box
  child: Text(
    "Lorem ipsum",
    style: TextStyle(
      fontSize: 24.0,
      fontWeight: FontWeight.w900,
      fontFamily: "Georgia",
    ),
  ),
  width: 320.0,
  height: 240.0,
  color: Colors.grey[300],
);

In flutter, because there is no markup language, we need to nest widget classes to implement our UI. The container widget class here is actually equivalent to div tag.

If you have written a non JSX react, you will find that the code style is a bit likeReact.createElementMy painting style.

React.createElement("div", {
    class: "test-c",
    style: "width: 10px;"
}, "Hello", React.createElement("span", null, "world!"));

layout

To implement a UI, the second important point is layout,
In the front end of web, the core of layout is the property of CSS

<div class="greybox">
  <div class="redbox">
    Lorem ipsum
  </div>
</div>
<style>
.greybox {
  background-color: #e0e0e0; /* grey 300 */
  width: 320px;
  height: 240px;
  font: 900 24px Roboto;
  display: flex;
  align-items: center;
  justify-content: center;
}
.redbox {
  background-color: #ef5350; /* red 400 */
  padding: 16px;
  color: #ffffff;
}
</style>

In flutter, some official style classes are needed, such as boxdecoration class to decorate the whole box, alignment to determine text alignment, and so on

var container = Container( // gray box
  child: Center(
    child:  Container( // red box
      child: Text(
          "Lorem ipsum",
          style: bold24Roboto,
          textAlign: TextAlign.center,
        ),
        decoration: BoxDecoration(
          color: Colors.red[400],
        ),
        padding: EdgeInsets.all(16.0),
      ),
      alignment: Alignment.center,
  ),
  width: 320.0,
  height: 240.0,
  color: Colors.grey[300],
);

interactive

Web:

<input name="account" />
<div onclick="handleSubmit()">Submit</div>

The last point is interaction. Similar to most front-end UI frameworks, each component actually exposes some event hooks,

Through these hooks, we can capture the user’s behavior and realize the corresponding logic,

The demo here simply realizes the basic interaction such as input verification, button click and submit.

Flutter:

// ...
children: <Widget>[
  TextFormField(
    decoration: InputDecoration(
        hintText: 'Email/Name/Telephone',
        labelText: 'Account *',
      ),
      onSaved: (String value) {
        loginForm.account = value;
      },
      validator: (String value) {
        if (value.isEmpty) return 'Name is required.';
      }
  ),
  RaisedButton(
    child: Text(
      'Login'
    ),
    onPressed: () {
      //Print ('submit operation ');
      // dosomething with loginForm
      handleSubmit()
    },
  ),
]

The rest includes routing, animation, gesture and other interactions. I won’t say more here. Most of the interactions that can be realized with web technology can be realized in flutter

It can be seen that the design idea of the UI part of flutter is similar to react except that there is no JSX.

So, after a brief introduction of the syntax, let’s see how to write an app

Start a flutter app

First of all, how to install the flutter development environment is not much to say, the official website tutorial has been very perfect

directory structure

Simply speaking, the directory structure, through theflutterAfter creating a project, such a directory structure will be automatically generated,

.
ι - Android # Android platform configuration, automatically generated by flutter
├ - IOS # IOS platform configuration, automatically generated by flutter
├ - assets ා static resource directory
ι - build š stores the release related files
Λ - lib # business code
├──  └──  main.dart   #App portal
└──  pubspec.yaml     #Package management file

Hello World

To start with a framework, of course, we need a classic Hello world.

To implement a flitter app,
We need to load the basic components of the flutterimport 'package:flutter/widgets.dart';
Then perform the basicrunAppThen a basic Hello world is complete.

//  main.dart  file
import 'package:flutter/widgets.dart';

void main() {
  runApp(
    Center(
      child: Text(
        'Hello, world!'
      ),
    ),
  );
}

The results are as follows

No surprise, you can also ignore the front-end flutter persuasion guide

As you can see, if there is no style, the application is a lump of black

Just like the UI framework such as ant design or iView that we like to use in front-end development, the development of flutter usually uses UI framework

Material App

Flutter has two sets of built-in UI components, namely material UI and Cupertino UI,

Now let’s see how the next material style app is implemented,
First, import material component

New a material app component, configure the title, APP bar and other information, and you can easily generate a material style app.

import 'package:flutter/material.dart';
void main() {
  runApp(
    MaterialApp(
     title: 'Hello App',
     home: Scaffold(
       appBar: AppBar(
         title: Text('Hello'),
       ),
       body: Center(
         child: Text(
           'Hello Flutter',
           style: TextStyle(
             fontSize: 30
           ),
         )
       ),
     ),
   )
  );
}

No surprise, you can also ignore the front-end flutter persuasion guide

More complicated, you can configure the routing information here, so I won’t talk about it here.

Through these, we know how to implement a flutter app. Then we can see that all the elements with entities are called widgets. Here, for the convenience of understanding, we collectively call them components.

Widgets

No surprise, you can also ignore the front-end flutter persuasion guide

Components are subdivided into stateless widget and stateful widget. It’s easy to think of the stateless component and stateful component of react

In fact, these two components of flutter are similar to those of react

Let’s first look at the stateless widget

Statelesswidget, a stateless component

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Hello App',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Hello'),
        ),
        body: Center(
            child: Text(
          'Hello Flutter',
          style: TextStyle(fontSize: 30),
        )),
      ),
    );
  }
}
  • StatelessWidgetFunction component corresponding to reactFunctional Component
  • HerebuildMethod corresponding to reactrendermethod

Let’s look at the stateful widget

Statefulwidget, a state component

The state of flutter consists of two classes: statefulwidget and state class.
Although the writing methods are different, the concepts are similar

  • StatefulWidgetcorrespondingReact.Component
  • stayStatefulWidgetClass manages the properties passed by the parent componentProp
  • stayStateClass to manage its ownState
  • adoptsetStateUpdate status
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Counter App',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Counter'),
        ),
        body: Center(
            child: Counter(10) ),
      ),
    );
  }
}


class Counter extends StatefulWidget {
  //This class is the configuration of state, where you can define the prop passed down by the parent component
  final int increaseNum;
  //Constructors
  Counter(this.increaseNum);
  
  @override
  _CounterState createState() => _CounterState();
}

class _CounterState extends State<Counter> {
  int _counter = 0;

  void _increment() {
    print('count: $_counter');

    setState(() {
      //The setstate callback tells the flutter to change the current state, and the call to setstate() triggers build() to update the view
      _counter += widget.increaseNum;
    });
  }

  @override
  Widget build(BuildContext context) {
    //The build method will be triggered every time setstate is called. At the same time, it is similar to react's render method,
    //In order to speed up the rebuild, the flutter framework has been optimized
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.center,

      children: <Widget>[
        RaisedButton(
          onPressed: _increment,
          child: Text('Increment'),
        ),
        Text('Count: $_counter'),
      ],
    );
  }
}

Have the students who have studied react ever felt familiar with this?

life cycle

Is the life cycle far behind when the component comes out?

Similar to react, flutter has its own component life cycle:

  • Initstate: initialization state
  • Didchangedependencies: state dependency changes
  • Build: build view
  • Didupdatewidget: state change, re render view
  • Activate: UI components are temporarily removed (such as switching pages)
  • Dispose: UI is permanently destroyed

No surprise, you can also ignore the front-end flutter persuasion guide

This is the end of our UI component section.

Cross platform development, “cross” in addition to the platform UI part, there are also cross platform developmentPlatform system service call

Native service call

No matter which cross platform development solution, it is basically to complete cross platform development at the UI level, and run multiple times at a time. However, when you need to complete specific functions, such as opening photo albums to get photos, it can’t be shaken at this level. You still need to use the native way to complete it.

For example, H5 itself is unable to call the underlying system API. In H5, we will use jsbridge to send commands to native so that native can call the system API.

In flutter, the government provides some plugins packages to implement common functions, such as local image selection, camera functions, etc., so that we can simply and directly use the system interfaces of different platforms.

Here is also a demo to evoke the camera:

import 'package:image_picker/image_picker.dart';

class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  File _image;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Image Picker Example'),
      ),
      body: Center(
        child: _image == null
            ? Text('No image selected.')
            : Image.file(_image),
      ),
      //Click the button to take a picture
      floatingActionButton: FloatingActionButton(
        onPressed: getImage,
        tooltip: 'Pick Image',
        child: Icon(Icons.add_a_photo),
      ),
    );
  }


  Future getImage() async {
    //Turn on the camera and get the picture resources
    var image = await ImagePicker.pickImage(source: ImageSource.camera);

    setState(() {
      _image = image;
    });
  }

}

So how do plug-ins call system services? Here we need to use the flutter’s methodchannel / platform channel communication mechanism.

Native service call – implement your own flutter plug

No surprise, you can also ignore the front-end flutter persuasion guide

As shown in the figure, flutter calls the API of native layer of different platforms through methodchannel mechanism. Because the code will eventually be compiled into machine code, the calling process is almost the same as the native call, which is lossless, unlike the bridge call, which requires protocol conversion.

To implement a flutter plug in for calling the underlying service, you canRefer to official documentsIn brief, the steps are as follows:

  1. API for defining plugin package
  2. Implement different underlying logic

    • Function realization of Android platform (Java / kotlin)
    • Function realization of IOS platform (Object-C / SWIFT)
  3. Using method channel to call native API in dart

persuade sb. to resign from an official position

After reading so much, do you feel that it’s not like persuasion, but a flutter article?

Don’t worry. I’ll give it up.

Although flutter looks very powerful, in fact, it has many limitations.

The domestic environment is complex and small programs are rampant

As we all know, domestic traffic is almost monopolized by several big companies, and the cost of APP promotion and download is also very high.

That’s why major companies have launched a variety of small programs

WeChat / Baidu / Alipay / byte beat / QQ applet and fast application…

In order to quickly drain, considering the input-output ratio, small companies are more willing to use the small program / fast application / H5 scheme than the app scheme with higher customer acquisition cost.

For example, Jingdong’staroFramework or similar cross end small program development framework is more in line with Chinese characteristics than flutter.

Taro is a multi terminal unified development framework, which supports the development of React code and generates applications that can run in WeChat / Baidu / Alipay / byte beat / QQ applets, fast applications, H5, React Native, and so on.

Abandoning web ecology

As you can see, in addition to the design idea of react style,Flutter has little to do with the front end

It is rumored that all applications that can be implemented with JS will be implemented with JS.

But unfortunately, based on various considerations, Google chose dart, which is not a popular language, as the development language of flutter, rather than JavaScript / typescript. It sets a certain threshold for the front-end development to contact the flutter.

However, flutter is not only for our front-end use. From the front-end point of view, we certainly want to use js / ts.
But for Android / IOS and other terminal development, it also needs a certain cost, which can be regarded as equal treatment.

Lack of community activity

Then, because dart language was brought up by flutter in the past two years, it was not popular until flutter came out. So far, dart’s community ecology and open source library are relatively deficient, unlike the front-end community, which has rich NPM packages.

Well, you can think about it. Have you ever heard dart before flutter?

Why does Google use dart as the development language of flutter?

It’s because
Dart also has a good father, orz, and his father is Google.

See, it’s so important to have a good father. Dart, the third tier language, won’t it be a big hit [funny]

Limitations of pure front end

Flutter completely solves the platform differences at UI level with self drawing engine, but as mentioned earlier,Differences of system hardware services (such as camera, Bluetooth and other services)It’s inevitable.

As a pure front end,IdeallyWith flutter, you can complete all the functions that can be realized by native.

But the reality is often not idealCross end development often encounter some platform related problems, such as the camera of the flutter plugin taking pictures, and there are some small bugs on a certain model of Android device.If you’re a pure front endIf you are lucky, you can find a solution in the open source community. If you are not lucky, you can only seek technical support from the terminal (IOS / Android) development.

Then, we need IOS / Android development as a cross end development framework,Is it still a cross end development framework?

To develop a mature app, do you dare to trust the pure front-end flutter?

of course,This is not a disadvantage of flutter, but a common problem of all cross platform solutions. If there were no such problem, react native would have been unified, and airbnb would not have abandoned react native.

as long asCross platform frameworkThere are platform difference bugs that need to be solved by programmers themselves, soPure front-end programmers are responsible for mobile developmentIt’s a pseudo proposition.

No surprise, you can also ignore the front-end flutter persuasion guide

So, is the flitter insulated from the front end?
That’s not the case.
If you want to develop a simple application that focuses on UI presentation and calls less system services, flutter is a good choice.

summary

In fact, we can see which programmers are most suitable for using flutter?

Not only IOS development, but also Android developmentThis does not require too proficient, can search to solve common terminal problems can be programmers. So learning flutter is like a tiger.

If you really want to be a flutter development engineer, you might as well learn Android and IOS development.

What talents are most popular in the Internet winter?

Versatile, comprehensive talents, explosive Stack Engineer

It’s over.


This article first appeared inGitHub blog
If the article is helpful to you,Your starIt’s my biggest support
Other articles:

Insert:
Shenzhen shopee long term push
Position: front end, back end (to go), product, UI, test, Android, IOS, operation and maintenance.
Salary and welfare: 20k-50k,It’s 7 o’clock, free fruit, free dinner, 15 days annual leave, 14 days paid sick leave.Position details referencePS: you can’t push those posted online.
Resume email: [email protected]
Or add my wechat: cwy13920

Recommended Today

Third party calls wechat payment interface

Step one: preparation 1. Wechat payment interface can only be called if the developer qualification has been authenticated on wechat open platform, so the first thing is to authenticate. It’s very simple, but wechat will charge 300 yuan for audit 2. Set payment directory Login wechat payment merchant platform( pay.weixin.qq . com) — > Product […]