During the last two days of National Day, I studied at home to organize a wave of FLUTTER, and basically went through all the codes that could be read and brushed. This article is quite long, so IT is suggested to save (STAR) and read it again. Portal: Nealyang Personal Blog
preface
After all, the front-end is basically a UI framework, but its engine is based on C++, the underlying is based on Skia rendering, DartVM and Text and so on…
On June 21, 2018, Google released the first preview release of Flutter, a new responsive, cross-platform, high-performance mobile development framework launched by Google Baba that is sure to become very popular. And it does seem to be getting hotter and hotter. Questions tagged [flutter]
In this article, we introduce the basic concept of Flutter, comb through common widgets, write common app demos, and write ~ Give up ~, hoping to help every beginner like me. Wrong place also hope god generous advice ~
International practice, blow a wave first ~
Move directly to Flutter official announcement PPT
On the Dart
As an introduction to Flutter, Dart will certainly be included. Of course, as an introduction to Flutter, Dart will not be covered much in advance.
Dart Portal: Dart or Dart2, or learn from Dart Chinese is also good.
Here’s why Dart is used.
Many language scientists believe that the natural language a person speaks affects the way they think. The Early Flutter team evaluated more than a dozen languages and chose Dart because it matched the way they built their user interface.
- Dart is AOT-compiled into fast and predictable native code, making Flutter almost entirely possible to write using Dart. This not only makes Flutter faster, but almost everything can be customized
- Dart can also be JIT compiled, the development cycle is extremely fast, the workflow is subversive, and also allows Flutter to achieve very Diao stateful thermal reloading.
- Dart makes it easier to create smooth animations and transitions that run at 60fps. Dart can do object allocation and garbage collection without locking. Like JavaScript, Dart avoids preemptive scheduling and shared memory (and therefore locks). Because Flutter applications are compiled to native code, they do not need to build slow Bridges between domains (for example, JavaScript to native code). It also starts up much faster
- Dart enables Flutter to eliminate the need for a separate declarative layout language, such as JSX or XML, or a separate visual interface builder, because Dart’s declarative programming layout is easy to read and visualize. With all layouts in one language and clustered in one place, Flutter easily provides advanced tools to make the layout simpler
- Dart is relatively friendly for IOS, Android, and Web FE.
Why Dart is chosen and why does Flutter choose Dart
About the Flutter
There are already RN, Weex, and other cross-platform mobile developments. What are the advantages of Flutter? Look at the pictures I stole from the Internet!
Photo credit: Jane Book
Everything is Widget
There is a saying that functional languages differ from imperative languages in that imperative languages give instructions to computers and functional languages describe logic to computers. This thinking is reflected in the Flutter UI. Flutter does not encourage manipulation of the UI. It certainly does not provide an API for manipulating views, such as textView.settext () or button.setonclick (). The description of the interface can be digitized (similar to XML, JSON, etc.), while the operation of the interface is difficult to be digitized, which is very important. Responsiveness requires convenient and sustainable mapping of data into the interface.
Widgets describe the interface in Flutter. Widgets are simply “configuration information” of a View. They are written to take advantage of some of the declarative features of the Dart language to achieve readability similar to structured Markup Language. Widgets form a hierarchy based on layout. Each widget is embedded in it and inherits its parent’s properties. There is no single “application” object; instead, the root Widget plays this role. In Flutter, everything is a Widget, even CSS styles.
<div class="greybox">
Lorem ipsum
</div>
.greybox {
background-color: #e0e0e0; /* grey 300 */
width: 320px;
height: 240px;
font: 900 24px Georgia;
}
Copy the code
In Flutter we write as
var container = new Container( // grey box
child: new Text(
"Lorem ipsum", style: new TextStyle(fontSize: 24.0 fontWeight: fontweight.w900, fontFamily:"Georgia",),), width: 320.0, height: 240.0, color: color.grey [300],);Copy the code
In flutter, the new TextStyle is required. TextStyle is a Widget. The style must be applied to child: text in the Container.
React is an example of how a widget describes a page’s UI. Its functionality classes are similar to XML in Android and JSX in React. Widgets convert to Elements during rendering. Element adds context information to widgets. Element is the instantiation node of the corresponding widget in the render tree. Because widgets are immutable, the same widget can describe nodes in multiple render trees at the same time. But an Element is a point that describes a particular location fixed in the render book. In a nutshell, widgets can be reused as a description, but Elements correspond to nodes that need to be drawn. Is element the final rendered view? Sorry, not yet. Element is converted to rendObject when drawn. RendObject is the object that actually goes through Layout and Paint and is drawn on the screen. There are three render related trees in Flutter: Widget Tree, Element Tree, and rendObject Tree. The rendering process of the three is as follows:
JSX -> Virtual Dom -> Real Dom
Well, the basic common widgets will be introduced later, along with some demos, and you’ll probably get a better sense of what this is all about.
Composition over Inheritance
Flutter borrows a lot from React ideas, even including state, which will be discussed later.
Widgets themselves are often made up of many smaller, single little widgets, so small that they don’t seem to make a difference. These widgets are combined to form a powerful custom Widget.
For example, a Container, which to Web FE might be a DIV, is made up of widgets that are responsible for layout, drawing, positioning, size, and so on. We can use various poses to combine them instead of inheriting them. The class hierarchy is shallow and wide, maximizing the number of possible combinations
Frame structure
Skia is a graphics Engine developed by Google that includes graphics, text, images, animation and other aspects. Skia is not only used in The Google Chrome browser, but also in the Flutter Engine. The Android system also uses Skia as a drawing processing engine.
The GPU to render:
State lifecycle:
As a beginner, see the above picture is a bit cloudy and foggy, and first do know ~
Flutter took a cursory look
There is no more to be said about the environment of Flutter
Hello World for the Material version of the basic Widget
Hello world
import 'package:flutter/material.dart'; class MyAppBar extends StatelessWidget{ MyAppBar({this.title}); // final Widget title; @override Widget build(BuildContext context){returnNew Container(height: 56.0, padding: const EdgeInsets. Symmetric (horizontal:8.0), decoration: new BoxDecoration( color:Colors.blue[400] ), child: Row( children: <Widget>[ new IconButton( icon:new Icon(Icons.menu), tooltip:'Navigation menu',
onPressed: (){
print('click on the Menu);
},
),
new Expanded(
child:new Center(
child:title
)
),
new IconButton(
icon:Icon(Icons.search),
tooltip:'Search',
onPressed: (){
print('Click the search button'); },)],),); } } class MyScaffold extends StatelessWidget{ @override Widget build(BuildContext context){return Material(
child: new Column(
children:<Widget>[
new MyAppBar(
title:new Text(
'Hello World',
style:Theme.of(context).primaryTextTheme.title
),
),
new Expanded(
child:new Center(
child:Text('Hello World!!! '() () [), (); } } voidmain(){
runApp(
new MaterialApp(
title:'My app',
home:new MyScaffold()
)
);
}
Copy the code
Github.com/Nealyang/fl…
This UI is really a bit sorry, the title above is blocked. Instead of adaptation, we will use the Scaffold provided by Material
The first example focuses on the code (remember the widgets you used) :
- Everything is Widget, and in front of Widget
new
Dispensable. - Class MyAppBar and MyScaffold use common widgets such as Container, Row, Column, Text, IconButton, Icon, BoxDecoration, Center and Expanded
- Container A widget that can be drawn, positioned, and resized. Like div, we can use it to create rectangular views. Container can be decorated as a BoxDecoration, such as a background, a border, ora shadow. A Container can also have margins, padding, and constraints applied to its size. In addition, Containers can be transformed in three dimensions using matrices.
- Row and Column are flex directions in flex layout
- Expanded fills up the remaining free space that has not yet been occupied by other children. Expanded can have multiple children. The Flex parameters are then used to determine how much of the remaining space they occupy. See the difference between Flexible and Expanded flutter controls for more details
- We define a MyAppBar class that accepts the title of a Widget in its constructor, which we can accept as well
String title
And then go to the class itselfnew Title(title)
- The runApp function takes the given Widget and uses it as the Widget root.
- The main job of a Widget is to implement a build function that builds itself. A widget usually consists of lower-level widgets. The Flutter framework builds these widgets in turn until the lowest child widgets, usually the RenderObject, are built, which calculates and describes the widget’s geometry.
Hello World with Material for basic interaction
import 'package:flutter/material.dart'; void main() => runApp(new MyApp()); Class MyApp extends StatelessWidget {MyApp extends StatelessWidget @override Widget Build (BuildContext context) {return new MaterialApp(
title: 'Flutter Demo', theme: new ThemeData(// This is the app theme set // After running you can see that the app has a blue toobar, and changing the code without exiting the app will update primarySwatch: Colors.blue, ), home: new MyHomePage(title:'Flutter Demo Home Page')); } } class MyHomePage extends StatefulWidget { MyHomePage({Key key, this.title}) : super(key: key); // This is an application base class that inherits from StateFulWidget, meaning that this class has a State object whose fields affect the APP UI. // This class is a configuration item for State. The constructor is used to get the value, which is typically consumed in State, using the final keyword. React defaultProps final String Title; @override _MyHomePageState createState() => new _MyHomePageState(); } class _MyHomePageState extends State<MyHomePage> { int _counter = 0; void_incrementCounter() {
setState(() {
// setThe State method tells Flutter that some values in the State have changed in order to update the new values to the UI in time if I don't passsetState changes the _count field so that the Flutter does not call the build anonymous function to update the _counter interface. }); } @override Widget build(BuildContext context) {// Build method will be used every timesetFor example, the _incrementCounter method above is called. // The Flutter has been optimized to rebuild the method, so you only update the parts of the Flutter that need to be updated. You don't have to update the smaller widgets in the Flutter separately, similar to the diff in ReactreturnNew Scaffold(appBar: new appBar (// Here we use the title value passed in from app. build to initialize MyHomePage to set our title title: new Text(widget.title), ), body: New Center(// Center is a layout Widget that has only one child and centers the child's Widget: New Column(// Column is also a layout widget, it can have multiple sub-widgets // Column has many properties to control its size and the position of the sub-widgets, Here we use mainAxisAlignment to center the children on a vertical line. // Here the main axis is vertical because Column is vertical, which can be roughly imagined as display:flex, The flex - directions: the column, the align - item, justifyContent... mainAxisAlignment: MainAxisAlignment.center, children: <Widget>[ new Text('Hello World! ', style: TextStyle (fontSize: 24.0, color: Colors. RedAccent decorationStyle: TextDecorationStyle. Dotted, fontWeight: FontWeight.bold, fontStyle: FontStyle.italic, decoration: TextDecoration.underline ) ), new Text('You have pushed the button this many times:',
),
new Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: new FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment', child: new Icon(Icons.add),),// The last comma is useful for formatting code); }}Copy the code
- Stateless widgets are immutable, which means their properties cannot change — all values are final
- To implement a StatefulWidget, at least two classes were required: 1) a StatefulWidget class; 2) A State class. The StatefulWidget class itself is unchanged, but the State class is always present throughout the widget’s life cycle
- If you need to change, you need to recreate it. StatefulWidget can save its own state. The question is, since widgets are immutable, how can they be stored? Flutter preserves State by introducing State. When the State changes, the node and the child’s Widget tree can be rebuilt to make UI changes. Note: If the State needs to be changed actively, it needs to be triggered by setState(). Simply changing the data will not cause the UI to change.
There is also the key part, which is not introduced here. In fact, it is similar to the concept of the key in React, which facilitates diff and improves efficiency. For details, see Key
Here we have seen some basic uses of Flutter, including the application of widgets, style writing and event registration. If we learn some more about routing, requests and caching, we can develop our own APP
OK, strengthen the writing interface, let’s do some demo ~
Layout of the Widget
After writing their own, found that with the official website to achieve different code address
Specific implementation can refer to the official website tutorial
Without going into details here, let’s take a look at understanding and feeling layouts and common layout widgets.
From a front-end point of view, when it comes to drawing the interface, it may be more sensitive to the layout
! [img](! [IMAGE](quiver-image-url/F4BD928A46B63086BE446CC582FB40D4.jpg =878×367))
Of course, here we still talk about the current commonly used Flex layout, basically get the page from large to small split as shown in the figure above.
Therefore, the Widget layout is mostly used by Row and Column. However, because of the idea that Flutter is all about components, other CSS layout widgets, such as Containers, may be needed. In fact, we understand as a block element!
The following is a quick demonstration of some commonly used widgets, but I won’t bother with Row and Column here. Portal: Layout Widget
Container
You can add padding, margin, border, and background color, often used to decorate other widgets
Code linked to Nealyang/flutter
class MyHomePage extends StatelessWidget{
@override
Widget build(BuildContext context){
Container cell (String imgSrc){
returnThe new Container (decoration: new BoxDecoration (border: border. All (width: 6.0, color: Colors. Black38), borderRadius: BorderRadius. All (const Radius. Circular (8.0))), Child: image.asset ('images/$imgSrc', width: 180.0, height: 180.0, fit: boxfit.cover,),); }return Container(
padding: const EdgeInsets.all(10.0),
color: Colors.grey,
child: new Column(
mainAxisSize: MainAxisSize.min,
children:<Widget>[
new Container(
margin: const EdgeInsets.only(bottom:10.0),
child: new Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children:<Widget>[
cell('1.jpg'),
cell('2.jpg'Margin: const EdgeInsets. Only (bottom:10.0), child: new Row(mainAxisAlignment: MainAxisAlignment.spaceAround, children:<Widget>[ cell('3.jpg'),
cell('4.jpg'() [(), [(), [(). }}Copy the code
The layout uses a Container for each image to add a rounded gray border and margin. Then use the container to change the column background color to light gray.
GridView
Scrollable grid layout, understood as display: grid
The GridView provides two prefabricated lists that automatically scroll when the GridView detects that the content is too long. If you need to build a custom grid, use gridView.count or gridView.extent to specify the number of columns allowed and the maximum pixel width of an item.
Code linked to Nealyang/flutter
List<Container> _buildGridTileList(int count) {
return new List<Container>.generate(
count,
(int index) =>
new Container(child: new Image.asset('images/${index+1}.jpg')));
}
Widget buildGrid() {
returnNew GridView.extent(maxCrossAxisExtent: 150.0, padding: const EdgeInsets. All (4.0), mainAxisSpacing: 4.0, crossAxisSpacing: 4.0, children: _buildGridTileList(10)); } class MyHomePage extends StatelessWidget{ @override Widget build(BuildContext context){returnnew Center( child: buildGrid(), ); }}Copy the code
MaxCrossAxisExtent = maxCrossAxisExtent = maxCrossAxisExtent = maxCrossAxisExtent
new GridView.count(
primary: false, padding: const EdgeInsets. All (20.0), crossAxisCount: 3, children: <Widget>[const Text()'He\'d have you all unravel at the'), const Text('Heed not the rabble'), const Text('Sound of screams but the'), const Text('Who scream'), const Text('Revolution is coming...'), const Text('Revolution, they...'),],)Copy the code
Specify the number of columns directly via crossAxisCount.
Stack
Cascading layout, position is absolute jio~
Use Stack to organize widgets that need to overlap. Widgets can completely or partially overlap the bottom widget. The first widget in the sublist is the Base widget; Subsequent child widgets are overlaid on top of the base widget. The contents of the Stack cannot scroll. A bit like weex with absolute set. The bottom component is always on top of the top component.
ListView
Scrollable long list that can be horizontal or vertical.
Card
Material style components, cards, AntD, etc component libraries often appear in the type of components.
In Flutter, cards have rounded corners and shadows. Changing the Card’s elevation property can control the shadow effect.
ListTile
Material style component, which I understand as the common list Item style, with up to three lines of text and optional ICONS at the beginning and end of the line
Code linked to Nealyang/flutter
conclusion
From the perspective of my superficial Flutter skills, the biggest difficulty may be that I cannot find an appropriate Widget to achieve the desired layout or effect, even the CSS style applied to the Widget. For example, Opacity is a Widget, not a CSS style
So for Flutter, we need to play around with more demos, just like many others on the Internet
For more information on Flutter for Web Developers, see the tutorial on Flutter for Web Developers
It’s only just begun
Everything about Flutter is based on widgets. Getting rid of widgets is just like getting rid of English words.
Don’t worry, don’t worry, borrow Zhang Shengge’s picture to give everyone to dissipate anger ~
Therefore, Flutter has a huge system of components that takes a lot of time to comb through.
! More importantly: practice
Originally the last chapter is a demo to explain ~
Unfortunately, the time assessment was inaccurate and the holiday inertia was missed… Consider the length, fill up the imitation XXX Demo bar ~~
Study and communication
Welcome to pay attention to personal wechat public number: full stack front selection, access to first-hand article push and free full stack ebook sharing benefits
Reference links && Good articles recommended
- The principle of Flutter and its practice
- Flutter goes from entry to advance
- The Widget that gets onto the car quickly
- In-depth understanding of Flutter interface development
- The difference between Flexible and Expanded flutter controls
- Commonly used widgets
- Practice of the Flutter React programming paradigm
- Detailed description of Flutter layout
- Build the layout in Flutter
- Because Chinese website
The Demo is recommended
- Tetris mini-game based on Flutter
- Open source Chinese client based on Google Flutter
- Live chat APP
- Super complete Flutter project maintained on personal Github
- Shanzhai nuggets
- First video