Flutter Web initial experience of technology that makes front-end developers unemployed.

  flutter, javascript

Flutter is a new type of “client” technology. Its ultimate goal is to replace the development of almost all platforms: iOS, Android, Web, desktop; It was written once and operated in many places. Mastering Flutter web may be the only chance for Web front-end developers to turn over the game.

图片描述

At the Google IO 2019 annual developer conference held a few days ago, Flutter web, as a brilliant technology, was highly sought after by developers. This is another milestone version after Flutter supports Android, IOS and other devices, and other embedded devices such as windows, linux, Macos and chroms will be supported later. Flutter itself is a multi-terminal unified cross-platform solution similar to RN, WEEX, hHybrid, etc. It has really been written once and run in many places. Its development exceeds the imagination of many people and is worthy of front-end developers’ attention. Today, let’s experience Flutter Web.

Overview

Let’s first take a look at Flutter, an open source mobile application software development kit developed by Google, which is used to develop applications for Android and iOS. It will also be the main tool for developing applications under Google Fuchsia. Since Flutter version 1.5.4, the development of the Web side has been supported. It uses Dart language for development. Compared with JavaScript, Dart is almost as fast as JavaScript in JIT (just-in-time compilation) mode. But when Dart runs in AOT mode, Dart performance is higher than JavaScript.

Flutter has built-in UI interface, which is different from cross-platform technologies such as Hybrid App and React Native. Flutter neither uses WebView nor native controls of each platform, but implements a rendering engine with unified interface to draw UI. Dart is directly compiled into binary files, which can ensure the consistency of UI of different platforms. It can also reuse Java, Kotlin, Swift or OC codes to access native system functions on Android and iOS, such as bluetooth, camera, WiFi, etc. Our company’s Now live broadcast, penguin counseling and other projects, Ali’s free fish and other commercial projects have been widely used.

Architecture

Flutter 的 Mobile 架构

Flutter’s top layer is a framework written with drat, which includes UI interfaces of Material(Android style UI) and Cupertino(iOS style). The following are common Widgets (components), followed by animation, drawing, rendering, gesture library, etc.
Below the frame is the engine, which is mainly written in C/C ++. The engine includes three core libraries. Skia is Flutter’s 2D rendering engine, which is Google’s 2D graphics processing function library, including fonts, coordinate conversion, and bitmaps, and has high performance and concise performance. Skia is cross-platform and provides a very friendly API. The second is Dart runtime environment and the third text rendering layout engine.
The lowest embedded layer, it is concerned with how to combine pictures on the screen and render them into pixels. The function of this layer is to solve cross-platform problems.

After learning about FLutter, let me talk about today’s highlight, Flutter for Web. If you want to know why Flutter can run on the web, you have to look at its architecture first.

Flutter 的 web架构

Through comparison, we can find that the web framework layer is almost the same as that of mobile. Therefore, the UI code can be completely migrated from Android/IOS Flutter App to the Web without changing Flutter API only by re-implementing the engine and embedded layer. Dart can use the Dart2Js compiler to compile Dart code into Js code. Most native App elements can be implemented through DOM, while elements that DOM cannot implement can be implemented through Canvas.

Installation

Flutter Web development environment is set up. Take my windows environment as an example to explain. Other environments are similar. The installation environment is complicated and requires patience. Android development experience is the best.

1. InWindows platformIf developed, the official environmental requirement is Windows 7 SP1 or later (64-bit).

2、Java environment, install Java version 1.8+and configure environment variables, because android development depends on Java environment.

For Java program development, two JDK commands are mainly used: javac.exe and java.exe. Path: C:Javajdk1.8.0_181bin. However, since these commands do not belong to windows itself, path configuration is required to use them. Click Computer-Properties-Advanced System Settings, and click Environment Variables. Click “New” under the “System Variable” column to create a new system environment variable (or user variable, equivalent).

图片描述

(1) new-> variable name “JAVA_HOME”, variable value “C:Javajdk1.8.0_181” (i.e. JDK installation path)
(2) edit-> variable name “Path” and add “at the end of the original variable value; %JAVA_HOME%bin; %JAVA_HOME%jrebin”
(3) new-> variable name “CLASSPATH”, variable value “.” %JAVA_HOME%lib; %JAVA_HOME%libdt.jar; %JAVA_HOME%libtools.jar”

3、Android Studio editor, install Android Studio, version 3.0 or later. We need it to import Android license and manage Android SDK and Android virtual machines. (default installation is sufficient)

After the installation is completed, set up a proxy. File-“Setting-“in the upper left corner searches for a proxy and sets up a company proxy to speed up the download of Android SDK.

图片描述

After that, click the square box button (SDK Manager) in the upper right corner to select and install the SDK version, preferably Android 9 version and API28. There will be a long download process. SDK is a necessary code library for development. By default, Flutter uses the Android SDK version based on your adb (Android Debug Bridge, managed connection phone, packaged in SDK) tool version. If you want Flutter to use different versions of Android SDK, you must set the ANDROID_HOME environment variable as the SDK installation directory.

图片描述

There is a small mobile phone type button (AVD Manager) in the upper right corner to set up Android simulator and create a virtual machine. If you have an Android phone, you can also connect a USB interface instead of a virtual machine. This process is necessary for debugging. After the installation is completed, in AVD (Android Virtual Device Manager), click Run on the toolbar. The simulator starts and displays the startup screen of the selected operating system version or device. Represents the correct installation.

图片描述

4、Install Flutter SDK

There are many ways to download Flutter SDK to see which is more suitable for you:
Flutter.com downloads the latest Beta version for installation:https://flutter.dev/docs/deve …
You can also download it from the Flutter github project at:https://github.com/flutter/fl …
The newer the version, the better, not less than 1.5.4.

Extract the installation package zip to the path where you want to install Flutter SDK (e.g. C: Srcflutter; Note that do not install flutter to a path that requires some high permissions, such as C:Program Files). Remember, add it later to the path of the environment variable; C:srcflutterbin so that you can use flutter on the command line.

Use mirroring
As the dependence on installing Flutter in China may be limited, Flutter has set up a temporary image for Chinese developers. You can add the following environment variables to the user environment variables:
PUB_HOSTED_URL: https://pub.flutter-io.cn
FLUTTER_STORAGE_BASE_URL: https://storage.flutter-io.cn

图片描述

5. install Dart and Pub. Install webdev, stagehand

Pub is Dart’s package management tool, similar to npm, which is bundled for installation.
Dart installation address:http://www.gekorm.com/dart-wi …
The default installation is enough. After installation, remember Dart’s path and configure it into the environment variable PATH so that dart and pub can be used in the command line. The default path is: C:Program FilesDartdart-sdkbin
First install stagehand, which is a necessary tool to create a project. Check it outC:\Users\chunpengliu\AppData\Roaming\Pub\Cache\binDoes the directory contain stagehand and webdev? if so, add them to the path of the environment variable. if not, install them as follows:

pub global activate stagehand

Webdev is a web server similar to Koa, and performs the following command installation

pub global activate webdev
# or
flutter packages pub global activate webdev

6. The Configuration Editor installs Flutter and Dart plug-ins

Flutter plug-in is used to support Flutter development workflow (run, debug, thermal overload, etc.).
Dart plug-in provides code analysis (validation when entering code, code completion, etc.). Android Studio’s settings search Flutter and Dart in File File-》setting-》plugins–and restart after installation.

图片描述

The VS code setting searches for Flutter and Dart in extension-, and restarts after installation.

图片描述

7. Run flutter doctor

Open a new command prompt or PowerShell window and run the following command to see if any dependencies need to be installed to complete the installation:

flutter doctor

This is a long process, flutter will test your environment and install all dependencies until: No issues found! If there is any defect, it will be preceded by an x. You need to solve them one by one.

图片描述

Everything is ready!

Create application

1. start VS Code

Call view > commandpalette … (shortcut ctrl+shift+p)
Enter’ flutter’, and then select’ flutter: newwebproject’

图片描述

Enter a Project name (such as flutterweb) and press Enter
Specify where to place the item and press the blue OK button.
Wait for project creation to continue and display the main.dart file. At this point, a Demo is created.

图片描述

We saw the familiar HTML file and the project entry file main.dart
The index.html in the web directory is the entry file of the project. Main.dart initialization file, picture related resources in this directory.
Main.dart in lib directory is where the main program code is located.
Each pub package or Flutter project contains a pubspec.yaml It contains dependencies and metadata related to this project.
Yaml is the lint rule for the configuration project.
/dart_tool is a file generated by project packaging and running compilation, in which the page main program main.dart.js is located.

2. Debug Demo, open the command line, enter the root directory of the project, and execute:

webdev flutterweb

After compilation and packaging are completed, the default browser will be started automatically (or F5 is pressed) to look at the converted HTML page structure:

图片描述

Lib/main.dart is the main program, and the source code is very simple. the whole page is stacked with widgets, which is different from traditional html and css.

import 'package:flutter_web/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}

class MyHomePage extends StatelessWidget {
MyHomePage({Key key, this.title}) : super(key: key);

final String title;

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'Hello, World!'  ,
),
],
),
),
);
}
}

Different from flutter App application, we imported flutter_web/material.dart library instead of flutter/material.dart, because the interface of App is not completely universal with Web at present, but as Google develops, they will eventually be merged together.
Open pubspec.yaml (similar to package.json), you can see that there are only two dependency packages flutter_web and flutter_web_ui, both of which are open source on github. Dev has very few dependency pages, two compilation-related packages, and a static file analysis package.

name: flutterweb
 description: An app built using Flutter for web
 environment:
 # You must be using Flutter >=1.5.0 or Dart >=2.3.0
 sdk: '>=2.3.0-dev.0.1 <3.0.0'
 dependencies:
 flutter_web: any
 flutter_web_ui: any
 dev_dependencies:
 build_runner: ^1.4.0
 build_web_compilers: ^2.0.0
 pedantic: ^1.0.0
 dependency_overrides:
 flutter_web:
 git:
 url:  https://github.com/flutter/flutter_web
 path: packages/flutter_web
 flutter_web_ui:
 git:
 url:  https://github.com/flutter/flutter_web
 path: packages/flutter_web_ui

Actual combat

Next, we will create a download with graphics and text functions, and learn flutter according to examples. We will implement the page below. It is an upper and lower column layout, and the lower column is divided into left and right columns.

图片描述

Step 1: Change the main application content, open the lib/main.dart file and replace the class MyApp. First, the root component MyApp, which is a class component inherited from the stateless component, is the theme configuration of the project, and calls the home component in the Home attribute:

class MyApp extends StatelessWidget {
//root component of application
@override
Widget build(BuildContext context) {
return MaterialApp(
Title:' Tencent News Client Download Page',//Title in //meta
Debugshowcheckkedmodebanner: false,//turn off debugging bar
theme: ThemeData(
Primary swatch: colors.blue.//page theme Material style
),
Home: Home(), // start home page
);
}
}

The second step, in the Home class, is the top guide of the page we want to render, using the AppBar component, which includes a center page title and a search button on the right. Text can be styled like css.

class Home extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.white,
appBar: AppBar(
backgroundColor: Colors.white,
elevation: 0.0,
centerTitle: true,
Title: Text( // center text
"Download Page",
style:
TextStyle(color: Colors.black, fontSize: 16.0, fontWeight: FontWeight.w500),
),
//Search for icons and features
actions: <Widget>[
Padding(
padding: const EdgeInsets.symmetric(horizontal: 20.0),
child: Icon(
Icons.search,
color: Colors.black,
),
)
],
),
//Call the body rendering class, where multiple method calls can be added
body: Stack(
children: [
Body()
],
),
);
}
}

The third step is to create the main content of the page, one picture plus multiple texts, using text components and picture components. The page structure adopts flex layout. Since both Expanded Flex values are 1, the space will be evenly distributed between the two components. The SizedBox component is equivalent to an empty box and is used to set the margin distance.

class Body extends StatelessWidget {
 const Body({Key key}) : super(key: key);
 
 @override
 Widget build(BuildContext context) {
 return Row(
 crossAxisAlignment: CrossAxisAlignment.stretch,
 mainAxisAlignment: MainAxisAlignment.spaceBetween,
 children: <Widget>[
 Expanded( // left
 flex: 1,
 Child: Image.asset(// picture component
 "background-image. jpg"//this is a background map under web/assets/
 fit: BoxFit.contain,
 ),
 ),
 const SizedBox(width: 90.0),
 Expanded( // right
 flex:1,
 child: Column(
 mainAxisAlignment: MainAxisAlignment.center,
 crossAxisAlignment: CrossAxisAlignment.start,
 children: <Widget>[
 Text( // text component
 "Tencent News",
 style: TextStyle(
 color: Colors.black, fontWeight: FontWeight.w600, fontSize: 50.0, fontFamily: 'Merriweather'),
 ),
 Constsizedbox (height: 14.0),//sizedbox is used to increase spacing.
 Text(
 "Tencent News is a 24-hour, all-round and timely news product created by Tencent for users, providing users with efficient and high-quality information, video and live broadcast services.  The information is super new and complete, the content is exclusive and of high quality, and the topic comments are interactive. "  ,
 style: TextStyle(
 color: Colors.black, fontWeight: FontWeight.w400, fontSize: 24.0, fontFamily: "Microsoft Yahei"),
 textAlign: TextAlign.justify,
 ),
 const SizedBox(height: 20.0),
 FlatButton(
 OnPressed: () {}, // Response Event for Download Button
 color: Color(0xFFCFE8E4),
 shape: RoundedRectangleBorder(
 borderRadius: BorderRadius.circular(16.0),
 ),
 child: Padding(
 padding: const EdgeInsets.all(12.0),
 Child: Text ("click to download", style: textstyle (fontfamily: "opensans")),
 ),
 ),
 ],
 ),
 ),
 const SizedBox(width: 100.0),
 ],
 );
 }
 }

At this point, after the page is created, save and run webdev serve, you can see the effect.

Summary

FLutter web is a branch of FLutter. After developing App, Flutter code at UI level can be directly compiled into Web version without modification, which basically can achieve 100% reuse of code and has a good experience. Currently Flutter web, as a preview version, has exceeded expectations in terms of performance, ease of use and layout. The touch experience is quite good. Although the experience is worse than APP, it is much better than traditional web. Imagine Flutter’s App for iOS and Android is also giving away a free Web version, which is better than the experience developed by traditional web. Write once ,Run anywhere。 Why not?

I think with Google’s continuous optimization, the development experience will get better and better after the official version is released. Flutter developers will eat a large portion of H5. Flutter may bring some changes to the current client development mode and the division of labor. Flutter’s current development experience is not very good, but it has great potential and is worthy of front-end personnel to learn.

However, there are still some problems. Flutter web is prepared for the development of client developers (especially Android) and the learning cost is a bit high for front-end understanding. At present, FLutter web and flutter are still two projects, and the compilation environment is also separate. It is necessary to modify the reference of Flutter-related library as Flutter_web in the code, and the components cannot reach full universality. This Google promise is currently being solved. Google’s ultimate goal is to maintain 100% code portability among Web, mobile App, desktop win mac linux, and embedded version of Flutter code library.

Personally, the development experience is not so good, there are still many holes to step on, and the version changes quickly. There is also the problem of scarce community resources, which requires a long-term accumulation. Compatibility problem. After code conversion, a large number of web components are used. Besides chrome, there are still some compatibility problems.

Amway time

In the process of web development, we have all seen or used some strange techniques and tricks. this technique is collectively referred to as black magic. these black magic are scattered in all corners. in order to make it convenient for everyone to consult and learn, we have collected, sorted out and classified them, and made a project on github-awesome-blackmargic, I hope you love to study the developers can like, also hope you can share their unique skills, if you are interested can send us pr.

If you are interested in Flutter and want to know more about Flutter, join our QQ group (784383520).