preface

It’s been 9,012 years and I don’t need to tell you how popular Flutter is, as a long period of Flutter video tutorials on the nuggets front page proves.

So just as one must “get in” before one can “get out”, the front end must also understand Flutter before it can be discouraged.

From the perspective of the front-end, how is Flutter development different?

. Then discourage =_=. 【 If you want to be directly persuaded to leave, please slide to the last 】

What is a Flutter

First, what is a Flutter?

The official website explains:

Flutter is an open source SDK from Google that can build high-performance applications for mobile, Web, and desktop applications across platforms.

Of course, although flutter can be developed on both the Web and desktop, we will focus more on the mobile cross-platform development capabilities of Flutter.

Well, before Flutter, there were many cross-platform development frameworks, some of which were well knownXamarin for C#, nativescript for js, weex for ali, and react native for everyoneAnd there are even more lesser known ones

So how does Flutter stand out among all the cross-platform development frameworks?

Why Flutter?

  1. Low input and high output of a set of code, direct output of Android + iOS platform applications. This is a common advantage of cross-platform development frameworks.
  2. High efficiency development

With the Just-in-time (JIT) compilation function of Flutter, it can provide Hot Reload function for rapid application development. There is no Hot Reload development efficiency, this point front-end students should be deeply experienced. 3. The rich and elegant UI framework itself provides UI components in both Material Design and Cupertino style, not limited to the system’s OWN OEM. 4. High-performance applications provide the same performance as native applications. The AOT of Flutter compiles code to ARM binaries, uses its own drawing engine (Skia), and has direct access to underlying system services without Bridge dependencies. These enable Flutter to perform as well as its native application.

All of these are secondary. What’s the key?

Flutter has a good father!

React and React Native are facebook’s, Angular is Google’s, and Vue is the only one with no big company background. In fact, many open source frameworks in the community are actually incubated from within large enterprises.

Having a good dad, backed by Google dad, born with gold in his mouth, looks like the future is beyond measure. The framework’s stability and growth will be assured, giving the open source community confidence.

This is, fight dad for a while, always fight straight.

Without further ado, flutter is not limited to system Oems and offers better performance than other cross-platform frameworks, so why should Flutter be so good? We can explore this by looking at the Flutter framework.

Flutter frame construction

The frame structure of the Flutter is as follows:

Okay, I think you’ve seen this picture more than once. Understand may have been clear in the chest, do not understand may still be a face meng force.

So let me just say it briefly

From the top down, Framework, which is written in DART, from the top down,

  1. There are Material and Cupertino UI components that are packaged.
  2. The packaged UI components Material and Cupertino are assembled from more basic Widget components. The Widget is equivalent to the front HTML div, H1, SPAN tag elements.
  3. Moving on, the Widget layer is made up of Animation, Painting, and Gesture, which are all rendered by Rendering. There is a slight difference between the front-end UI structure (HTML), style (CSS), and event interaction (JS is separate, while Flutter is Widget).

Framework is Engine, the Framework of UI interaction is Engine to draw and render. Engine draws UI components inside the Engine layer through the Skia graphics Engine. Skia is Google’s open source 2D graphics Engine that works on multiple platforms. This is one of the core elements of Flutter that makes it cross-platform. This is why flutter is not limited to system OEM components. That is, if you want to encapsulate your own Ant-Design-inspired Flutter UI framework, you can build your own UI framework directly from the basic widgets. If the underlying UI doesn’t meet your needs. Dart allows you to call the Skia graphics engine API and draw your own UI without any restrictions.

Finally, there is the Embedded layer, which deals with platform differences so that Flutter applications can be embedded on various system platforms.

You can see that Flutter does not use the OEM of the native system, but uses the 2D rendering engine SKia to render the UI directly. This makes Flutter have a low platform-dependent layer. The platform only provides a canvas, and all the remaining render related logic is inside Flutter.

This is how Flutter is developed cross-platform. What are the advantages of this design? We can compare other application development architectures.

Cross-platform Architecture comparison

Native

First of all, let’s look at the architecture design of native APP development. Generally, an APP is divided into two parts, NAMELY UI rendering and system service invocation. Cross-platform development, as we often say, is actually across these two parts.

Native App UI will be implemented through native OEM controls provided by the platform,

System service calls, such as the use of cameras, Bluetooth and other sensors, will also be implemented through the API provided by the platform system

OEM controls and system service invocation specifications, and programming languages are not uniform across platforms. Android uses Java/Kotlin while iOS uses Objective-C/Swift, resulting in platform differences.

An APP needs to develop several sets of code, the UI effect may not be consistent, time-consuming and laborious.

Hence the need for cross-platform development.

Let’s take a look at common cross-platform architectures

Webview

First of all, the most common cross-platform solution is to directly use webView, which is actually referred to as hybrid app.

Although the webview kernel of different platforms may not be the same, but it will always follow w3c specifications, so our front-end code can run on the platform’s WebView, to achieve cross-platform development on UI

The system service invocation, on the other hand, uses the Bridge to invoke native methods via the protocol.

The disadvantages of hybrid App are also obvious. The performance of WebView is not as good as that of the original.

To solve this webView performance problem, the community has come up with another solution

React Native / Weex

As shown in the figure, React Native, Weex and other frameworks use front-end languages to describe systems such as OEM to achieve cross-platform. Simply speaking, they configure the page layout by writing JS and then parse it into native controls through React Native.

This way, the performance is significantly improved, because essentially the rendered, or native control.

However, even with the improved performance, it is still not at the native level, because RN parses jSBUnder file layouts through Jscore, which is still slightly different from native direct layouts.

React Native doesn’t eliminate the need to write native code. If you encounter complex platform-related issues, you’ll still have to dive into the native library to make necessary adjustments. Airbnb dropped RN last year for similar reasons.

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

Flutter

As mentioned earlier, The UI rendering of Flutter is based on the SKia image engine and does not depend on any system platform. The platform simply provides a canvas on which images can be rendered.

So just skip the native rendering mechanism and render the view from your own rendering engine, which is exactly the same as native, without the middleman to make the difference.

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

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

What about calls to system services? Flutter does not eliminate the problem of cross-platform system service calls, because the differences in hardware design and programming languages are almost inevitable.

However, unlike the previous methods of invoking system services in the form of bridge, flutter calls system services in the form of Platform channel. This will be skipped here and the communication mechanism will be described in the following sections in detail

Web VS Flutter

Development of language

Instead of a Web page divided into HTML, CSS and JS, everything in Flutter is widgets. The specific types of widgets are:

  • Elements of the widget. Such as Button, menu, list
  • Style widgets. Such as the font and color
  • The layout of the widget. Such as padding, margins
  • .

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

The UI grammar

Basic styles

With style syntax, we are familiar with the front-end code, using HTML and CSS to quickly implement a simple UI.

Let’s 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>
Copy the code
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]);Copy the code

With Flutter, because flutter doesn’t have a markup language, we need to nest Widget classes to implement our UI. In this case, the Container Widget class is essentially a div tag.

So if you look at this code style, if you’ve ever written a non-JSX React, you’ll notice that the code style is a bit like the React. CreateElement style.

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

layout

To implement a UI, the second most important point is the layout. In the front end of the Web, the core point of implementing the layout is the properties 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>
Copy the code

With flutter, there are some officially provided style classes, such as the BoxDecoration class here to decorate the 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]);Copy the code

interaction

Web:

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

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

With these hooks, we can capture the user’s behavior and implement the corresponding logic,

The demo here is a simple implementation of input verification, button click submission and other basic interaction.

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()
    },
  ),
]
Copy the code

Other interactions include routing, animation, gesture and so on. I won’t go into more details here. Most of the interactions that can be implemented using Web technology can be implemented in Flutter

As you can see, the UI of Flutter is designed in much the same way as react, except that there is no JSX.

So with the syntax out of the way, let’s actually see, how do you write an APP

Start a Flutter App

How do YOU install the Flutter development environment first

The directory structure

Briefly, a directory structure is automatically generated when a project is created using FLUTTER.

.├ ─ Android # Android platform Setup ├─ ios # ios platform Setup ├─ ├─ all exercises, ├─ ├─ all exercises, ├─ all exercises, ├── all exercises, ├── all exercises, ├── all exercises, ├── all exercises, ├── all exercises, ├── all exercises, ├── all exercises Pubspec.yaml # Package management filesCopy the code

Hello World

Start with a framework and, of course, create a classic Hello World.

To achieve a flutter app, we need to load the flutter the basic components of the import ‘package: flutter/widgets. The dart’; , then execute the basic runApp, and a basic Hello World is complete.

/ / the main dart files
import 'package:flutter/widgets.dart';

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

The effect is as follows:

As you can see, without a style, the application is a lump of black….

Just as we like to use a UI framework like Ant Design or iView for front-end development, flutter will be developed using a UI framework

Material App

There are two UI components built into Flutter, namely the Material UI and Cupertino UI.

Now let’s briefly look at how a Material style APP is implemented. First, import the Material component

New a MaterialApp component, configure the title, app bar and other information, and simply 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),))))); }Copy the code

To make things more complicated, you can configure routing information here, but I won’t go into details here.

From this we know how to implement a Flutter app. Then we can see that all the elements that have a body are called Widgets. For ease of understanding, we refer to them as components.

Widgets

Components were subdivided into Stateless widgets and Stateful widgets, which could easily be associated with react Stateless components and Stateful components

In fact, the two components of Flutter do resemble those of React

Let’s first look at stateless widgets.

Stateless component StatelessWidget

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),)))); }}Copy the code
  • StatelessWidgetReact function componentFunctional Component
  • Here thebuildMethod corresponding to reactrendermethods

Take a look at the state component

The state component StatefulWidget

The State of a Flutter consists of two classes: the StatefulWidget and the State class. It’s written differently, but the concept is the same:

  • StatefulWidgetThe correspondingReact.Component
  • inStatefulWidgetClass manages what the parent component passesProp
  • inStateClass to manage itselfState
  • throughsetStateUpdate the 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 a configuration of state, where you can define a prop passed by the parent component
  final int increaseNum;
  // constructor
  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 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) {
    // Each call to setState triggers the build method, and the react render method,
    // The Flutter framework has also been optimized to make rebuilds faster
    return Row(
      crossAxisAlignment: CrossAxisAlignment.center,
      mainAxisAlignment: MainAxisAlignment.center,

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

For those of you who learned React, do you have a sense of deja vu?

The life cycle

Component out, is the life cycle far behind?

Like React, Flutter has its own component lifecycle:

  • InitState: indicates the initialization state
  • DidChangeDependencies: State Dependency change
  • Build: Builds the view
  • DidUpdateWidget: State changes to re-render the view
  • Deactivate: UI component temporarily removed (e.g. switching pages)
  • Dispose: UI is permanently destroyed

This brings us to the end of our UI component section.

Cross-platform development “crosses” not only the platform UI part, but also the platform system service calls mentioned earlier.

Native service invocation

No matter what cross-platform development solution is, it is basically cross-platform at the UI level, running multiple places in one development. However, when you need to complete specific functions, such as opening albums to obtain photos, you still need to use the Native way to complete this level.

For example, H5 itself cannot call the underlying API of the system. In H5, we will use JsBridge to send commands to Native, so that native can call the system API.

With Flutter, plugins packages are provided to implement common functions, such as local image selection and camera functionality. This allows us to use the system interfaces of different platforms easily and directly.

An evocative camera demo is also provided here:

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 photo
      floatingActionButton: FloatingActionButton(
        onPressed: getImage,
        tooltip: 'Pick Image',
        child: Icon(Icons.add_a_photo),
      ),
    );
  }


  Future getImage() async {
    // Open the camera to shoot and get the image resource
    var image = awaitImagePicker.pickImage(source: ImageSource.camera); setState(() { _image = image; }); }}Copy the code

So how does a plug-in call a system service? This uses the methodchannel/platform channel communication mechanism of flutter.

Native service invocation – Implement your own Flutter Plugin

As shown in the figure, Flutter uses the methodChannel mechanism to call the apis of the native layer of different platforms. Because the code is eventually compiled into machine code, the call process is essentially the same as a native call, which is lossless, unlike a bridge call, which requires protocol translation.

To implement a FlutterPlugin for the underlying service invocation, please refer to the official documentation. The simple steps are as follows:

  1. Define the API for plugin package
  2. Implement different underlying logic
    • Android Platform function implementation (Java/Kotlin)
    • Function realization of iOS platform (Object-C/Swift)
  3. Call the native API in dart using the Method Channel

stop

After reading so much, doesn’t it feel like a Flutter rather than an exhortation?

Don’t worry. That’s it.

Flutter may seem powerful, but if you really think about it, it actually has some limitations.

Domestic environment is complex, small procedures run amok

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

That’s why companies have come up with a variety of mini-programs. So far, here’s what we know:

Wechat/Baidu/Alipay/Bytedance/QQ small programs and fast applications……

In order to facilitate rapid drainage, considering the input-output ratio, small companies are more willing to use small programs/quick applications /H5 schemes rather than App schemes with higher customer acquisition costs.

For example, JD.com’s Taro framework or a similar cross-end apPLETS development framework are more Chinese than Flutter.

Taro is a multi-application development framework that allows you to write code once using React development mode to generate applications that can run on wechat, Baidu, Alipay, Bytedance, QQ, fast apps, H5, React Native, etc.

Abandoned the Web ecosystem

As you can see throughout this article, flutter has very little to do with the front end, apart from the react-style design idea.

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

Unfortunately, for all these reasons, Google chose Dart, a not-so-popular language, instead of JavaScript/Typescript to develop Flutter. A certain threshold is set for front-end development to contact flutter.

However, flutter is not only for the front end, but also for the front end, we want js/ TS. But for Android/ios and other terminal development, in fact, also need a certain cost, can be regarded as equal.

Lack of community activity

Because dart language was carried up by the flutter for two years, it did not fire until the flutter came out. Dart’s community ecology, open source libraries, and so on are lacking, unlike the front-end community, which has rich NPM packages.

So, have you heard the Dart language before Flutter?

Why did Google use DART as the development language for Flutter?

It’s because… Dart also has a good father, Orz, who is also Google.

Dart: How important it is to have a good father

Limitations of pure front-end

Flutter uses a self-drawing engine to completely address platform differences at the UI level, but as mentioned earlier, there are inevitable differences in system hardware services (such as camera bluetooth).

Ideally, as a pure front-end, flutter can do all of the things it can do native.

However, the reality is not always ideal. Cross-end development often encounters platform-related issues, such as the camera taking of the Flutter Plugin and minor bugs on certain Android devices. If you’re a pure front-end, if you’re lucky you’ll find a solution in the open source community, if you’re unlucky you’ll have to turn to terminal (iOS/Android) development for technical support.

So, is there still a cross-platform framework for iOS/Android development, or a cross-platform framework?

To develop a mature App, would you trust the pure front-end with Flutter?

Of course, this is not a problem of Flutter, but a problem common to all cross-platform solutions. If it hadn’t been for this, React Native would have been dominant, and Airbnb wouldn’t have abandoned React Native.

As long as cross-platform frameworks have platform differences that programmers have to work out for themselves, it’s a bogus proposition for pure front-end programmers to be in charge of mobile development.

So is the flutter insulated from the front end? Not so. Flutter is a good choice if you want to develop a simple application that focuses on UI presentation and calls fewer system services.

conclusion

In fact, it can be seen that who are the best programmers to use Flutter?

Both iOS development, and some understanding of Android development, not too proficient, can search and solve common terminal problems can be programmers. Then learning flutter is like adding wings to a tiger.

If there is someone interested in developing Flutter as a developer, then learn about Android and iOS development.

Who is the most popular talent in Internet winter?

Versatile, comprehensive talent, stack explosion engineer…

End of persuasion.




If articles are helpful to you, your star is my biggest support for other articles:

  • Json you don’t know the browser, Module, and main fields priority
  • You can play it this way? Super useful Typescript built-in and custom types
  • Front-end performance optimization is not entirely north


Position promotion in the long term: front end, back end (to go), product, UI, testing, Android, IOS, operation and maintenance. Salary and benefits: 20K-50K😳, 7 PM off 😏, free fruit 😍, free dinner 😊, 15 days annual leave (), 14 days paid sick leave. Position details for reference. PS: net cast cannot push inside oh. Resume email: [email protected] or add me to wechat: CWY13920