Flutter is a new type of “client” technology. Its ultimate goal is to replace development across almost every platform: iOS, Android, Web, desktop; Done a compilation, more than a run. Mastering Flutter Web may be the only chance for web front-end developers to turn the game around.

At the Google IO 2019 Developer Conference held recently, Flutter Web was touted by developers as one of the exciting technologies. This is another milestone for Flutter following its support for Android and IOS devices, as well as Windows, Linux, Macos, Chroms and other embedded devices. Flutter itself is a multi-terminal unified cross-platform solution similar to RN, WEEX, hHybrid, etc. It is truly written at one time and run in many places. Its development is beyond many people’s imagination and deserves the attention of front-end developers. Today we will experience Flutter Web.

An overview of

Take a look at Flutter, an open source mobile app development kit developed by Google for Android and iOS, which will also be the main tool for developing apps under Google Fuchsia. Since Version 1.5.4 of FLutter, Development on the Web side has been supported. It is developed using the Dart language, which is almost as fast as JavaScript in JIT mode. But Dart performs better than JavaScript when running in AOT mode.

Flutter has a built-in UI. Unlike cross-platform technologies such as Hybrid App and React Native, Flutter uses neither a WebView nor Native controls from each platform. Instead, Flutter implements a unified rendering engine to draw its UI. Dart is compiled directly into binaries, which ensures consistent UI across platforms. It can also reuse Java, Kotlin, Swift, or OC code to access native system features on Android and iOS, such as Bluetooth, camera, WiFi, and more. Our company’s Now Live streaming, Penguin Tutoring and other commercial programs, such as Ali Leisure Fish, have been widely used.

architecture

The top layer of Flutter is a framework written in DRAT. It contains the Material (Android style UI) and Cupertino (iOS style UI) UI. Below that, there are common Widgets, followed by animation, drawing, rendering, gesture library, etc. Skia is the 2D rendering engine for Flutter. Skia is a 2D graphics processing function library for Google, including font, coordinate conversion, and bitmap, all of which are efficient and concise. Skia is cross-platform and provides a very friendly API. The second is the Dart runtime environment and the third text rendering layout engine. The lowest embedding layer, which is concerned with combining images onto the screen and rendering them into pixels. This layer is designed to address cross-platform capabilities.

Now that I know about FLutter, I want to talk about FLutter for Web, which is the highlight of the day. To understand why Flutter works on the Web, you need to take a look at its architecture.

By comparison, the Web framework layer is almost identical to mobile’s. Therefore, UI code can be ported from the Android/IOS Flutter App to the Web without changing the Flutter API by re-implementing the engine and embed layer. Dart can compile Dart code into Js code using the Dart 2JS compiler. Most native App elements can be implemented through DOM, and elements that can’t be implemented through DOM can be implemented through Canvas.

The installation

Build up the Flutter Web development environment. Take my Windows environment as an example to explain. Other environments are similar, and the installation environment is cumbersome and requires patience.

1, inThe Windows platformThe official environment requirement for development is Windows 7 SP1 or later (64-bit).

2,Java environment, install Java 1.8 + and configure environment variables, because Android development depends on the Java environment.

For Java program development, the main use of JDK two commands: javac.exe, java.exe. Path: C: javajDK1.8.0_181bin. However, these commands are not Windows commands, so you need to configure paths to use them. Click Computer – Properties – Advanced System Settings, and click Environment Variables. Click Add under System Variables to create a new system environment variable (or user variable, equivalent).

C: javajDk1.8.0_181 (JDK installation Path) C: JavajDk1.8.0_181 (JDK installation Path) %JAVA_HOME%bin; %JAVA_HOME%jrebin “(3) Create a new -> variable name” CLASSPATH “, variable value “. %JAVA_HOME%lib; %JAVA_HOME%libdt.jar; The % JAVA_HOME % libtools. The jar”

3,Android Studio editor, install Android Studio 3.0 or later. We need it to import Android licenses and manage the Android SDK and Android virtual machines. (Default installation)

After the installation is complete, set the proxy, File- “setting-” in the upper left corner of the proxy, set the company proxy, used to speed up the download of Android SDK.

Then click the box button (SDK Manager) in the upper right corner to install the SDK version, preferably Android 9 version, API28, which will take a long time to download. The SDK is a necessary code base for development. By default, the Android SDK version that Flutter uses is based on your ADB tool version (Android Debug Bridge, packaged with SDK). If you want Flutter to use a different version of the Android SDK, you must set the ANDROID_HOME environment variable to the SDK installation directory.

In the upper right corner is a small phone-type button (AVD Manager) to set up the Android emulator and create a virtual machine. If you have an Android phone, you can also connect it to a USB port instead of a virtual machine. This process is necessary for debugging. After the installation is complete, in the Android Virtual Device Manager (AVD), click Run on the toolbar. The emulator starts and displays a splash screen for the selected operating system version or device. Represents proper installation.

4,Install the Flutter SDK

There are several ways to download the Flutter SDK to see which one is more suitable for you: download the latest Beta of the Flutter SDK from the Flutter website and install it: Flutter. Dev /docs/deve.. … You can also download the Flutter Github project at github.com/flutter/fl…. The newer the better, no lower than 1.5.4.

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

Due to restrictions on the dependencies associated with Flutter installation in China, Flutter officials have created temporary images for Chinese developers. You can add the following environment variables to the user environment variables: https://pub.flutter-io.cn FLUTTER_STORAGE_BASE_URL: https://storage.flutter-io.cn

5. Install Dart and Pub. Install WebDev and Stagehand

Pub is a package management tool for Dart, similar to NPM, bundled with installation. Dart installation: www.gekorm.com/dart-wi… After installation, remember the path to Dart and configure it in the environment variable path so that Dart and pub can be used on the command line. The default path is: C:Program FilesDartdart-sdkbin install StageHand first, stageHand is a necessary tool to create the project. Check the C: Users\ ChunpengLiu \AppData\ Pub\Cache\bin directory to see if it contains stageHand and webdev. If it does, add it to the environment variable path. If not, install it as follows:

pub global activate stagehandCopy the code

Webdev is a KoA-like Web server. Run the following command to install it

pub global activate webdev
# or
flutter packages pub global activate webdevCopy the code

6. Configure the Editor to install the Flutter and Dart plug-ins

The Flutter plugin is used to support the Flutter development workflow (running, debugging, thermal reloading, etc.). The Dart plug-in provides code analysis (validation as code is entered, code completion, and so on). For Android Studio, go to “File-” setting- “plugins-” to search for Flutter and Dart, install and restart.

VS Code Settings search for Flutter and Dart in Extension – and restart 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 doctorCopy the code

This is a long process that flutter will detect your environment and install all dependencies until: No issues found! , if there is any missing, will put an X in front of that item. You need to deal with them.

All ready!

Create an

1. Start VS Code

Call the View > Command Palette… Enter ‘flutter’ and select ‘flutter: New Web Project’.

Enter a Project name (such as FlutterWeb), then press Enter to specify where to place the Project, then press the blue OK button to wait for the Project creation to continue and display the main.dart file. At this point, a Demo is created.

We see the familiar HTML file and the project entry file main.dart. The index.html file in the Web directory is the entry file for the project. Dart initialization file, image related resources in this directory. Dart, in the lib directory, is where the main program code resides. Each PUB package or Flutter project contains a pubspec.yaml. It contains dependencies and metadata associated with this project. The analysis_options.yaml is the lint rule to configure the project. /dart_tool is the file generated by the compilation of the project package run, and the main page program main.dart.js is in it.

2, debug Demo, open the command line, enter the project root directory, execute:

webdev flutterwebCopy the code

After compiling and packaging, launch the default browser automatically (or press F5) and take a look at the structure of the converted HTML page:

Lib /main.dart is the main application. The source code is very simple, and the entire page is stacked with widgets, unlike 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!', ), ], ), ), ); }}Copy the code

Dart library instead of Flutter_web /material. Dart. This is because currently the App interface is not completely generic to the Web. They will eventually be merged together. When you 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 compile-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 the path: packages/flutter_web flutter_web_ui: git: url: https://github.com/flutter/flutter_web path: packages/flutter_web_uiCopy the code

In actual combat

Next, we will create an illustrated download to learn about Flutter from examples. We will implement the page shown below. It is a two-column layout, with the lower column divided into left and right columns.

Dart file and replace class MyApp with the root component MyApp, which is a class component that inherits stateless components and is the subject configuration of the project. It calls the home component in the home property:

Class MyApp extends StatelessWidget {override Widget Build (BuildContext context) {return MaterialApp( Title: 'the tencent news client download page', / / in the titile of meta debugShowCheckedModeBanner: false, / / off debugging bar theme: ThemeData (primarySwatch: Color.blue, // page theme Material Style), home: home (), // launch the home page); }}Copy the code

The second step, in the Home class, is to render the top of the page using the AppBar component, which contains a center page title and a right search button. 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: 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, here can add more methods to call the body: Stack(children: [ Body() ], ), ); }}Copy the code

The third step is to create the body content of the page, using a text component and an image component. The page structure uses a Flex layout. Since the Flex value of both Expanded is 1, the space will be evenly divided between the two components. The SizedBox component acts as an empty box 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(// Image component "backgrounds-image.jpg ", // This is the result of the web/ implies/fit: Box fit. contain,), const SizedBox(width: 90.0), Expanded(// right flex:1, child: Column(mainAxisAlignment: MainAxisAlignment.center, crossAxisAlignment: CrossAxisAlignment.start, children: <Widget>[Text(// TextStyle(color: color.black, fontWeight: fontweight.w600, fontSize: 50.0, fontFamily: 'Merriweather'),), const SizedBox(height: 14.0),// SizedBox is used to increase the space between Text(" Tencent News is a 24-hour, all-round, timely news product for users, providing users with efficient and high-quality news, video and live services. TextStyle(color: colors.black, fontWeight: fontweight.w400, fontSize: 24.0, fontFamily: "Microsoft Yahei"), textAlign: Textalin.justify,), const SizedBox(height: 20.0), FlatButton(onPressed: () {}, Color(0xFFCFE8E4), Shape: RoundedRectangleBorder(borderRadius: borderRadius. Circular (16.0),), child: Padding(Padding: const EdgeInsets. All (12.0), child: Text(" click ", style: TextStyle(fontFamily: "Open Sans")),),),),),), const SizedBox (width: 100.0),,); }}Copy the code

At this point, the page is created, save, run Webdev Serve, and you can see the effect.

conclusion

FLutter Web is a branch of FLutter. After the development of App, the FLutter code at the UI level can be directly compiled into the Web version without modification, which can basically achieve 100% reuse of the code and has a good experience. The current Flutter Web preview exceeds expectations in terms of performance, ease of use, and layout. The touch experience is good. Although not as good as the APP experience, it is much better than the traditional Web. Imagine that Flutter’s iOS and Android App gives away a free Web version that is better than the traditional Web development experience. Write once, Run anywhere. Why not?

I think that with Google’s continuous optimization, the development experience of Flutter will get better and better after the official release, and the developers of Flutter will eat up a large share of the H5. Flutter may bring some changes and changes in the division of labor to the current client development mode. The current development experience of Flutter is not good, but it has great potential and is worth learning by the front-end staff.

However, there is still a part of the problem. Flutter Web is designed for 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. The reference of FLutter related library needs to be modified to Flutter_web in the code. The components are not yet fully universal, and this is being addressed by Google. Google’s ultimate goal is to maintain 100% code portability between the Web, mobile App, desktop Win MAC Linux, and embedded version of the Flutter code base.

Personally, the development experience is not very good, there are still many pits to step on, the version changes quickly. There is also the problem of scarce community resources, which need to be accumulated over a long period of time. Compatibility issues, the code conversion uses a lot of Web Components, other than Chrome, compatibility issues.

Amway time

In the course of web development, we have all seen or used some strange techniques, which we collectively call dark magic, and these dark magic is scattered everywhere. In order to make it easy for you to check and learn, we have collected, sorted and categorized them, and created a project on Github called awesome-Blackmargic. I hope you love to study the developers can like, but also hope you can share their unique skills, if interested can send pr to us.

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