Tencent's technical team arranges the articles of the year, and it's easy to get a thorough introduction to Flutter, making the front end bigger in seconds

Original author: Tencent Technology
Original link: https://zhuanlan.zhihu.com/p/90836859
Source: Zhihu

This article really introduces the technical features of Flutter in a comprehensive way. If you've heard about Flutter, you want to know about it, but you don't want to read the thick API, then this article is for you.

With the pure client to Hybrid technology, to RN & weex, and to today's Flutter technology, client implementation technology continues to advance. In a previous APP project, we chose weex because of historical reasons. With the deepening of use, we gradually found that the rendering performance of weex has become a hidden danger and bottleneck. With the continuous maturity and popularity of Flutter technology, the good cross platform and high-performance advantages of Flutter continue to attract us.

(this article contains the following contents, which will take about 18 minutes to read.)

  • 1. What's flutter?
  • 2. Cross platform technology comparison of mobile end
    2.1 H5 + native APP
    2.2 RN&Weex
    2.3 Flutter
  • 3.Dart language
  • 4. Environment configuration
  • 5.Hello World
    5.1 create project
    5.2 project structure
    5.3 start simulator
    5.4 launch project APP
    5.5 simplified version of Hello World
    5.6 add status to the page
    5.7 summary
  • 6. routing
    6.1 jump of single page
    6.2 use routing table for more page jumps
    6.3 route parameters
  • 7.widget
    7.1 Text
    7.2 Button
    7.3 Container
    7.4 Image
  • 8. layout
    8.1 row & column & center row & column axis layout
    8.2 Align angle positioning layout
    8.3 Stack & positioned absolute positioning
    8.4 flex & Expanded streaming layout
  • 9. animation
    9.1 simple animation: fade in and out
    9.2 more complex animation: zooming in and out
  • 10.http request
    10.1 HttpClient
    10.2 http
    10.3 Dio
  • 11. vomit
    11.1 walls
    11.2 over design of components
    11.3 too many nesting not suitable
    11.4 layout modification will cause nesting relationship modification
    11.5 Dart language upgrade
    11.6 no hot update
  • 12. conclusion

1. What's flutter?

Flutter is Google's mobile UI framework, which can quickly build high-quality native user interface on iOS and Android.

  • It has cross platform development features and supports IOS, Android and Web.
  • The characteristics of heat and heavy load greatly improve the development efficiency
  • The self drawing UI engine and the way of compiling into native code make the high performance of system runtime possible
  • Using Dart language, it supports compiling into Web code at the same time,

Is it worth following up on Flutter technology? If you look at the comparison of search indexes of Flutter, Weex and react native, you will probably know the trend of this industry.

The blue color is Flutter, which shows that the upward trend is very strong. This is the front end of bitter force. If you don't follow the trend, the trend will abandon you.

2. Cross platform technology comparison of mobile end

Why is there such a thing as Flutter? What's his principle? How does he achieve high performance? To understand these problems, we have to start from the comparison of several mobile cross platform technologies.

2.1 H5+ native APP

The lowest technical threshold, the fastest access speed and the most convenient hot update are naturally H5 mode. APP provides a Webview to use Http direct connection of H5 page. APP and H5 can be developed independently of each other. JS uses Bridge to communicate with native data. The display interface relies on Webview's browser rendering. But the problem is also obvious, because it requires remote direct connection, so the first time you open the H5 page, there will be a momentary white screen, and Webview itself will have at least tens of meters of memory consumption.

Of course, as a front-end developer, you can use SPA single page, lazy loading, offline H5 and other front-end optimization methods to optimize performance in H5 mode, so as to make H5 performance closer to the original. But for the first time, the communication efficiency of Bridge is low, which is always limited by the technical framework.

2.2 RN&Weex

Because of the disadvantages of H5, the front-end engineer who loves to toss and turns out two big killers, RN and Weex, uses the native to analyze the display configuration of Rn and Weex, and the display layer and logic layer directly communicate with the native data. Because the browser is abandoned, the natural rendering performance and execution performance are greatly improved.

However, every time there is a display change, JS will adjust the rendering through the Bridge and the native transition, so the Bridge finally becomes a performance bottleneck. In the actual project, especially when doing a lot of complex animation processing, because the rendering part needs frequent communication, the performance problem becomes particularly prominent. Interested students can have a look BindingX , which has a detailed description of the low frame rate of animation caused by the low efficiency of data communication in animation.

2.3 Flutter

I have to admire the imagination of Google developers. In order to achieve the ultimate performance, flutter takes a step forward. After the compilation of flutter code, it is the native code directly, and uses the native way of self drawing UI engine to render. Flutter relies on a Skia 2D graphics engine . Skia is also the underlying rendering engine of Android platform and Chrome, so there is no need to worry about the performance. Because Dart is used to compile AOT into native, the performance of AOT is naturally faster than that of JS in V8 engine, and because the Bridge is removed, there is no cumbersome data communication and interaction, the performance will go a step further.

3.Dart language

Learn about dart before you learn about it. Dart language was ambitious to replace Javascript, but the timing of its release coincided with the rapid development of JS, so it gradually fell silent, and only with the release of Flutter did it regain its vitality.

Last in September 2019 Google Developers Conference With the release of flutter 1.9, the current Dart is also updated to version 2.5 Provides machine learning and cross platform call to C. Generally speaking, Dart grammar is very easy for front-end students to start with, and the style is very similar.

For Dart syntax, move to the portal: https://dart.dev/samples

4. Environment configuration

No matter what new language you learn, the first thing is environment configuration. As Flutter comes from Google, there is a certain threshold. If you install it in the company, you need a convenient agent switching tool, such as: Proxifier .

For installation tutorial, refer to the official website: https://flutter.dev/docs/get-started/install

Flutter supports a variety of editors such as Android studio, Xcode. However, since it is recommended to support cross two terminal development VSCode.

After VSCode installation, you need to install the Flutter plug-in and Dart plug-in. In the extension window, search for the Flutter and Dart, and click "Install", which is very convenient.

If you can't install it, remember to turn on the next agent.

5.Hello World

As a great programmer, the first line of code always starts with Hello World. A kind of

5.1 create project:

Method 1: directly use the command to create:

flutter create projectname

Method 2: use VSCode to create:

View - > command palette - > shuttle: new project

Note that please open the agent first, or your creation progress will be stuck all the time.

5.2 project structure

Drag the project into VSCode to see the directory structure. In the automatically created project, we see that Android and IOS related running environment have been brought.

The main entry file is main.dart. You can open it to familiarize yourself with it. It's ok if you don't understand it for the time being. I'll talk about it later.

Another important file is pubspec.yaml, which is the configuration file of the project and will be modified later.

5.3 start simulator

Click the emulator in the lower right corner of VSCode to start the emulator. (VSCode will automatically find the emulator in Android environment, IOS environment, and real environment.)

5.4 launch project APP

Select Main.dart, click debug - > start debugging, the project will start debugging and run in the simulator.

5.5 simplified version of Hello World

In fact, as soon as Flutter comes up, he uses StatefulWidget to make an auto add Demo, which is not very friendly to novices. I still like to step by step, first delete those complex auto increasing logic, we only do the simplest static page display based on StatelessWidget. (what are StatefulWidget and StatelessWidget? Later)

main.dart

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatelessWidget{
   @override
  Widget build(BuildContext context) {
       return Scaffold(
            appBar: AppBar(
              title: Text("I am Title"),
            ),
            body: Center(
                    child: Text(
                        'Hello World',
                    )
            )
      );
  }  
}

In the above code, you can see clearly the simplest page hierarchy:

MaterialApp -> MyHomePage -> Scaffold -> body -> Center -> Text

**What is Scaffold? **It's a page Scaffold of Flutter. You can understand it as an HTML page. The difference is that in addition to the Body, it also provides attributes such as the TitleBar at the top of the appBar, and the navigation bar at the bottom of the bottom of the bottom navigation bar.

Display effect:

This is the simplest page. There is no interaction, only display. However, in the actual business scene, it is unlikely that all pages are of this kind. The data on the page is generally returned from the interface, and then it is dynamically rendered on the page. At this point, you need to use stateful widget with state

5.6 add status to the page

Give yourself a requirement. When the button is clicked, change the text "Hello World" displayed on the page to "You Click Me"

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: MyHomePage(),
    );
  }
}

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

class MyHomePageState extends State<MyHomePage>{
   var msg="Hello World"; //msg default text
   @override
   Widget build(BuildContext context) {
       return Scaffold(
            appBar: AppBar(
              title: Text("I am Title"),
            ),
            body: Center(
                      child:Column(
                              children:<Widget>[
                                  Text(msg), //Display text based on variable value
                                  FlatButton(
                                      color: Colors.blue,
                                      textColor: Colors.white,
                                      //Click the button to modify the text of msg
                                      onPressed: () {
                                        setState(() {
                                          this.msg="You Click ME";
                                        });
                                      },
                                      child: Text(
                                        "Click ME",
                                        style: TextStyle(fontSize: 20.0),
                                      ),
                                  )
                              ]
                      )
                  )
      );
  }  

}

Execution effect:

The key code above is this:

 onPressed: () {
         setState(() {
                this.msg="You Click ME";
          });
 },

I believe that students who have written small programs are familiar with this setState_

5.7 summary

StatelessWidget: a stateless change, UI static curing Widget, with higher page rendering performance.
Stateful Widget: a Widget that can cause UI changes due to state changes. Stateful widgets are used when it comes to data rendering scenes.

Why are there two? StatelessWidget has all the functions, StatefulWidget?

There is only one answer: performance, performance, performance

In stateful widget, because to maintain state, its life cycle is more complex than StatelessWidget. Every time setState is executed, it will trigger
window.scheduleFrame() causes the whole page's widget to be refreshed, and the performance will be reduced.

Students who have used small programs should have some experience in this regard Official documentation for applets It is strongly recommended to reduce the use frequency of setData to avoid performance degradation. But flitter is more radical. It launched StatelessWidget and directly cut off the use of setState in the Widget.

The page structure is as follows:

6. routing

The actual project has many different pages. The jump between pages needs to use routing. We add a list page, click the "Click Me" button on the Home page to jump to the list page.

6.1 jump of single page

Add list.dart

import 'package:flutter/material.dart';

class ListPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    //Define a list of list widget s
    List<Widget> list=<Widget>[];

    //Demo data definition
    var data=[
      {"id":1,"title":"test data AAA","subtitle":"ASDFASDFASDF"},
      {"id":2,"title":"test data bbb","subtitle":"ASDFASDFASDF"},
      {"id":3,"title":"test data ccc","subtitle":"ASDFASDFASDF"},
      {"id":4,"title":"test data eee","subtitle":"ASDFASDFASDF"},
    ];

    //According to Demo data, construct ListTile component list
    for (var item in data) {
      print(item["title"]);

      list.add( ListTile( 
          title: Text(item["title"],style: TextStyle(fontSize: 18.0) ),
          subtitle: Text(item["subtitle"]),
          leading:  Icon( Icons.fastfood, color:Colors.orange ),
          trailing: Icon(Icons.keyboard_arrow_right)
      ));
    }

    //Back to the entire page
    return Scaffold(
      appBar: AppBar(
        title: Text("List Page"),
      ),
      body: Center(
        child: ListView(
          children: list,
        )
      ),
    );
  }
}

Add the introduction of list page in main.dart

import 'list.dart';

Modify the button event on the Home page and add the Navigator.push jump

FlatButton(
          color: Colors.blue,textColor: Colors.white,
          onPressed: () {    
                       Navigator.push(context, MaterialPageRoute(builder:(context) {
                                return  ListPage();
                       }));
              },
           child: Text("Click ME",style: TextStyle(fontSize: 20.0) ),
    )

The core method is: Navigator.push(context,MaterialPageRoute)

Jump example:

6.2 use routing table for more page jumps

In MaterialApp, there is a property called routes. We can name routes, so that when we jump, we only need to use the corresponding route name, such as Navigator.pushNamed(context, RouterName). Click two different buttons to jump to ListPage and Page2 respectively.

Main.dart is modified as follows:

import 'package:flutter/material.dart';
import 'list.dart';
import 'page2.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      //Route table definition
      routes:{
        "ListPage":(context)=> ListPage(),
        "Page2":(context)=> Page2(),
      },
      home: MyHomePage(),
    );
  }
}

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

class MyHomePageState extends State<MyHomePage>{
   @override
   Widget build(BuildContext context) {
       return Scaffold(
            appBar: AppBar(
              title: Text("I am Title"),
            ),
            body: Center(
                      child:Column(
                              children:<Widget>[
                                  RaisedButton(
                                      child: Text("Clikc to ListPage" ),
                                      onPressed: () {
                                        //Jump according to the named route
                                         Navigator.pushNamed(context, "ListPage");
                                      },
                                  ),
                                   RaisedButton(
                                      child: Text("Click to Page2" ),
                                      onPressed: () {
                                          //Jump according to the named route
                                         Navigator.pushNamed(context, "Page2");
                                      },
                                  )

                              ]
                      )
                  )
      );
  }  

}

Example:

When we have routing, we can start to use different pages in a project to learn different functions.

6.3 route parameters

To jump from the list page to the details page, you need to route parameters. How is this done in the flitter system?

First, in main.dart, add the routing configuration of the detail page DedailPage

//Route table definition
      routes:{
        "ListPage":(context)=> ListPage(),
        "Page2":(context)=> Page2(),
        "DetailPage":(context)=> DetailPage(), //Add routing configuration of detail page
      },

And modify the click event of ListTile in ListPage, add route jump transfer parameter, here is to transfer the entire item data object

ListTile( 
          title: Text(item["title"],style: TextStyle(fontSize: 18.0) ),
          subtitle: Text(item["subtitle"]),
          leading:  Icon( Icons.fastfood, color:Colors.orange ),
          trailing: Icon(Icons.keyboard_arrow_right),
          onTap:(){
            //When clicking, jump to route and transfer parameters
             Navigator.pushNamed(context, "DetailPage", arguments:item);
          },
      )

In the detail page, get the parameters and display them

import 'package:flutter/material.dart';
class DetailPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
     //Get route parameters
     final Map args = ModalRoute.of(context).settings.arguments;

    return Scaffold(
      appBar: AppBar(
        title: Text("Detail Page"),
      ),
      body: 
        new Column(
          children: <Widget>[
             Text("I am Detail page"),
             Text("id:${args['id']}" ),
             Text("id:${args['title']}"),
             Text("id:${args['subtitle']}")
          ],
        )
      );
  }
}

Demo effect:

7.widget

Flutter provides many default components, and the components of each component are inherited from the widget. In the eyes of flutter: everything is a widget. Does this sentence look familiar? Remember in webback, everything is a module? Similarly, everything in java is an object. It seems that philosophy is the guiding ideology of any technology.

widget, as a visual UI component, includes two parts: display UI and function interaction. Large widgets can also be composed of multiple small widgets.

Common widget components:

7.1 Text

Demo:

Text(
         "Hello world",
         style: TextStyle(
                      fontSize: 50,
                      fontWeight: FontWeight.bold,
                      color:Color(0xFF0000ff)
                  )
    ),

Text style, from another widget: TextStyle. The color in TextStyle is another instance of widget Color.

If you use the indent method of fluent, it really looks a little ugly. The front-end students who are used to writing CSS can have a look at the following styles:

Text( "Hello world", style: TextStyle( fontSize: 50,fontWeight: FontWeight.bold,color:Color(0xFF0000ff) ) )

Is it easier to write in one line? Is this a front-end vice? A kind of

7.2 Button

There are many kinds of buttons for flutter. Let's see their differences:

RaisedButton: raised button
FlatButton: flatten button
Outline button: button with border
Icon button: button with Icon

Button test page dart:

import 'package:flutter/material.dart';

class ButtonPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text("Button Page"),
      ),
      body: Column(
        children: <Widget>[
             RaisedButton(
                  child: Text("I am RaiseButton" ),
                  onPressed: () {},
              ),
               FlatButton(
                  child: Text("I am FlatButton" ),
                  color: Colors.blue,
                  onPressed: () {},
              ),
              OutlineButton(
                  child: Text("I am OutlineButton" ),
                  textColor: Colors.blue,
                  onPressed: () {},
              ),
              IconButton(
                  icon: Icon(Icons.add),
                  onPressed: () {},
              )  
        ]
      )
    );
  }
}

Demo:

What to use in the project? Take what you need~

7.3 Container

Container is a very common widget, which is usually used as a container. Let's take a look at his basic attributes first. By the way, what does he look like in HTML?

Basic attributes: width, height, color, child

body: Center(
        child: Container(
           color: Colors.blue,
           width: 200,
           height: 200,
           child: Text("Hello Container ",style:TextStyle(fontSize: 20,color: Colors.white)),
        )
      )

Padding

We can also use padding to expand the interior without setting width and height

Container(
           color: Colors.blue,
           padding: EdgeInsets.all(30),
           child: Text("Hello Container ",style:TextStyle(fontSize: 20,color: Colors.white)),

        )

Margin

We can also use margin to expand the offset outside the container,

Container(
           color: Colors.blue,
           padding: EdgeInsets.all(30),
           margin: EdgeInsets.only(left: 150,top: 0,right: 0,bottom: 0),
           child: Text("Hello Container ",style:TextStyle(fontSize: 20,color: Colors.white)),
        )

Transform

We can also change the rectangle by using tansform, for example, rotating an angle

Container(
           color: Colors.blue,
           padding: EdgeInsets.all(30),
           child: Text("Hello Container ",style:TextStyle(fontSize: 20,color: Colors.white)),
           transform: Matrix4.rotationZ(0.5)
        )

See here, a lot of front-end students to say, so familiar. Yes, it's just like one thing in Html: DIV, you can really strengthen your understanding accordingly.

7.4 Image

Network picture loading

Using NetworkImage, you can load network pictures:

child:Image(
          image: NetworkImage("https://mat1.gtimg.com/pingjs/ext2020/qqindex2018/dist/img/qq_logo_2x.png"),
           width: 200.0,
        )  

Local picture loading

Loading a local image is a little more complicated. First, you need to add the path configuration of the image to the pubspec.yaml configuration file mentioned earlier:

Use AssetImage when loading local pictures:

child:Image(
               image: AssetImage("assets/images/logo.png"),
                width: 200.0,
            )      

You can also use shorthand:

 Image.asset("assets/images/logo.png",width:200.0)

There are many components provided by flutter. We will not give examples here, but we suggest you look at the API: https://api.flutter.dev/

8. layout

We already know so many components, so how to draw a complete page? This is the part of the page layout.

8.1 row & column & center row & column axis layout

The literal meaning is also well understood. Row layout, column layout, and center layout are all widget s for Flutter.

The difference is that row and column are widgets with multiple children, while Center is a widget with only one child.

 Row(
     children:<Widget>[]
 ) 

 Column(
     children:<Widget>[]
 )    

 Center(
      child:Text("Hello")
 )

8.2 Align angle positioning layout

We often need to display the contents in the Container in the upper left corner, the lower left corner, the upper right corner and the lower right corner. In the era of html, CSS can be easily implemented, but in flutter, you must rely on Align to locate the Widget

Example of positioning in the lower right corner:

 child: Container(
           color: Colors.blue,
           width: 300,
           height: 200,
           child: Align(
                      alignment: Alignment.bottomRight,
                      child:Text("Hello Align ",style:TextStyle(fontSize: 20,color: Colors.white)),
                  )
        )

Display effect:

Alignment provides a variety of positioning options, which is quite considerate.

8.3 Stack & positioned absolute positioning

Of course, there is also the requirement of absolute positioning. In css, position: absolute is used to solve this problem. However, in fluent, two widget s, stack+ positioned, need to be used together.

Stack: supports element stacking
Positioned: supports absolute positioning

child:Stack(
              children: <Widget>[
                  Image.network("https://ossweb-img.qq.com/upload/adw/image/20191022/627bdf586e0de8a29d5a48b86700a790.jpeg"),
                  Positioned(
                    top: 20,
                    right: 10,
                    child:Image.asset("assets/images/logo.png",width:200.0)
                  )
              ],
            )

8.4 flex & Expanded streaming layout

Flex flow layout is familiar to students as a front-end. The Row and Column mentioned before are actually inherited from flex and also belong to flow layout.

If the axis is uncertain, use Flex to set the axis by changing the value of direction
If the axis has been determined, use Row and Column to make the layout more concise and semantic

Flex test page:

class FlexPage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text("Flex Page"),
      ),
      body:  Flex(
          direction: Axis.horizontal,
          children: <Widget>[
            Container(
              width: 30,
              height: 100,
              color: Colors.blue,
            ),
            Expanded(
              flex: 1,
              child: Container(
                height: 100.0,
                color: Colors.red,
              ),
            ),
            Expanded(
              flex: 1,
              child: Container(
                height: 100.0,
                color: Colors.green,
              ),
            ),
          ],
        ),
    );
  }
}

In the example, the containers are arranged horizontally and axially, with a fixed width on the left and two Expanded on the right, each accounting for half of the remaining width.

9. animation

Now that Flutter has said that everything is a Widget, including animation implementation, which is also a Widget. Let's take a look at an example

9.1 simple animation: fade in and out:

Use the out of the box Widget provided by flutter:

import 'package:flutter/material.dart';

class AnimatePage extends StatefulWidget {
  _AnimatePage  createState()=> _AnimatePage();
} 

class _AnimatePage extends State<AnimatePage> {
  bool _visible=true;
  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text("Animate Page"),
      ),
      body: 
          Center(

            child: Column(
                  children: <Widget>[
                      AnimatedOpacity(
                        opacity: _visible ? 1.0:0.0,
                        duration: Duration(milliseconds: 1000),
                        child: Image.asset("assets/images/logo.png"),
                      ),

                      RaisedButton(
                        child: Text("Display hiding"),
                        onPressed: (){
                          setState(() {
                            _visible=!_visible;
                          });
                         },
                      ),

                  ],
                ),
          )    
      );

  }
}

Among them, AnimatedOpacity is the Widget of animation transparency change, and the Image controlled by transparency change is the child element of AnimatedOpacity. This is totally different from the previous way of front-end animation. We need to change the way of thinking.

Demo effect

9.2 more complex animation: zooming in and out

When writing complex animations, there is no corresponding widget component, so you need to use Animation, AnimationController, and Tween.

Animation: saving animation values and states
AnimationController: controls animation, including: start forward(), stop(), reverse() and other methods
Tween: provide begin and end as the value range of animation change
Curve: set animation to use curve changes, such as non-uniform animation, acceleration first, and then deceleration.

Animation example:

class AnimatePage2 extends StatefulWidget {
  _AnimatePage  createState()=> _AnimatePage();
} 

class _AnimatePage extends State<AnimatePage2>  with SingleTickerProviderStateMixin {

  Animation<double> animation;
  AnimationController controller;

  initState() {
    super.initState();
    controller =  AnimationController(duration:  Duration(seconds: 3), vsync: this);

     //Using elastic curves, data changes from 0 to 300
     animation = CurvedAnimation(parent: controller, curve: Curves.bounceIn);
     animation = Tween(begin: 0.0, end: 300.0).animate(animation)
      ..addListener(() {
        setState(() {
        });
      });

    //Start animation (forward execution)
    controller.forward();
  }

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text("Animate Page"),
      ),
      body: 
          Center(
              child: Image.asset(
                  "assets/images/logo.png",
                  width: animation.value, 
                  height: animation.value
              ),
            )  
      );   
  }

  dispose() {
    //Animation resources need to be released during route destruction
    controller.dispose();
    super.dispose();
  }

}

It is very important to release the animation resources when the route is destroyed, otherwise it is easy to cause memory leakage.

Show Demo:

10.http request

To do business logic, you can't do without http request. Next, let's see how http request of flutter is done.

10.1 HttpClient

httpClient can be used in dart:io library without introducing a third-party library. The example code is as follows:

Use example

import 'dart:convert';
import 'dart:io';

Future _getByHttpClient() async{
    //Interface address
    const url="https://www.demo.com/api";

    //Define httpClient
    HttpClient client = new HttpClient();
    //Define request
    HttpClientRequest request = await client.getUrl(Uri.parse(url));
    //Define reponse
    HttpClientResponse response = await request.close();
    //The data returned by respine is a string
    String responseBody = await response.transform(utf8.decoder).join();
    //Close httpClient
    client.close();
    //String needs to be converted to JSON
    var json= jsonDecode(responseBody);
    return json;

} 

Generally speaking, the code is quite tedious and inconvenient to use.

10.2 http

This is the third-party class library provided by Dart.dev, address: https://pub.dev/packages/http

Need to add class library application in pubspec.yaml first

dependencies:
  flutter:
    sdk: flutter
  json_annotation: ^2.0.0
  http: ^0.12.0+2

Use example:

Future _getByDartHttp() async {
  // Interface address
 const url="https://www.demo.com/api "; / / get the return value of the interface
 final response = await http.get(url);
 //The return value of the interface is converted to JSON
 var json = jsonDecode(response.body); 
 return json;
}

This method is much simpler than the httpClient above.

Dio

The most widely used third-party library in China is the digital third-party library provided by flutterchina on github. At present, there are more than 5800 stars.

Official website address: https://github.com/flutterchina/dio

Using Dio, because it is a third-party library, you also need to add the third-party library reference in pubspec.yaml first.

dependencies:
  flutter:
    sdk: flutter
  json_annotation: ^2.0.0
  dio: 2.1.16

Use example:

import 'package:dio/dio.dart';

Future _getByDio() async{

      // Interface address
      const url="https://www.demo.com/api";

      //Define Dio instance
      Dio dio = new Dio();
      //Get the Response returned by dio
      Response response = await dio.get(url);
      //Return value converted to JSON
      var json=jsonDecode(response.data);
      return json;
}

The interface call is also much simpler than httpclient. Perhaps due to the fact that fluterchina highly recommends this DIO Library in his official tutorial, the third-party library is currently the most widely used. Unlike Dart.dev's http, it needs a new instance of DIO. When creating an instance, it can also pass in more extended configuration parameters.

BaseOptions options = new BaseOptions(
    baseUrl: "https://www.xx.com/api",
    connectTimeout: 5000,
    receiveTimeout: 3000,
);
Dio dio = new Dio(options);

11. vomit

In the process of learning Flutter, actually there are still many frustrations and need to Tucao.

11.1 walls

Because there is a wall in the wall, you need to switch back from the inside of the wall to the outside when you configure the flitter, or download the flitter plug-in and the third-party library.

11.2 over design of components

There are many widget components provided, but the real core components and common components are also those. For example, the relationship between Flex and column, row, for example, the relationship between Tween and more than 20 Tween subclasses, such as IntTween, ColorTween, SizeTween, etc., requires a lot of effort to see the implementation differences of each specific subclass.

11.3 too many nesting not suitable

Because there are many nesting levels, and the layout, animation, and functions are all together. For the first time, Flutter and Dart are used. This nesting relationship is very confusing, which can only be overcome slowly. In addition, developing more customized components can make the nesting relationship look clearer.

11.4 layout modification will cause nesting relationship modification

In the front-end html+css separation world, the layout can be adjusted by modifying CSS without changing the nesting relationship. But in the Flutter, because the layout is also nested, it is necessary to change the nesting relationship. To make nesting easier and change less, it is particularly important to split pages into subcomponents.

11.5 Dart language upgrade

Yes, language upgrading will also cause learning problems. There are new and old materials out there. For example, some are new Text(), some are Text(), and novices will feel dizzy on the road. In fact, this is caused by Dart language upgrade. Remember that after Dart upgrade 2.X, it will not use new. You can read Dart's upgrade and change instructions if you are interested.

11.6 no hot update

In the middle of the year, Google officially announced that flutter does not officially support hot update, but the free fish team has its own hot update plan. As for the hot renewal, we can only watch it change. Performance, development efficiency, and thermal update are always trade-offs. Even for the free fish team, the hot update costs a little bit of performance degradation. Is that the original intention of choosing fluent? Still that sentence: weigh the gains and losses.

12. conclusion

With the release of Flutter 1.9 and flutter for web by Google in September, the component-based idea of Flutter makes it possible for a code to cross three ends. I believe that the future of Flutter will be broader.

This is not a tutorial, but a little experience in the process of learning Flutter. Due to the time relationship, the research is not in-depth. If there is any omission, please do not hesitate to give me some advice.

Learning and sharing

After all, I have worked in Samsung Xiaomi for many years, and I know the direction of technological reform and innovation. As a cross platform development technology, flutter has quickly captured people's hearts with its beauty, speed, efficiency, openness and other advantages. However, many fans of flutter have advanced learning materials. Today, I share the learning materials I collected and collated with those in need. If there is any information about F Lutter advanced learning can discuss and communicate with my ultimate choice of communication group in cross platform development of flutter. Download address: https://shimo.im/docs/yTD3t8Pjq3XJtGv8

Download address: https://shimo.im/docs/yTD3t8Pjq3XJtGv8

402 original articles published, 716 praised, 140000 visitors+
His message board follow

Tags: JSON Android hot update Google

Posted on Tue, 14 Jan 2020 02:55:30 -0800 by gilbertwang