当前位置:网站首页>Xiao He shows his sharp corners and says hello to flutter app
Xiao He shows his sharp corners and says hello to flutter app
2022-07-26 05:59:00 【Juntong】
first Flutter application
today , Let's read it together Flutter Code after project initialization !
Create an
adopt
ASCreate a newFlutterengineering , We will get a default counter application exampleProject
dartThe code is mainly inlib/main.dartin
class MyApp extends StatelessWidget {@overrideWidget build(BuildContext context) {return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,),
home: MyHomePage(title: 'Flutter Demo Home Page'),);}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('You have pushed the button this many times:'),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
The code analysis
1. Import package
import 'package:flutter/material.dart';
Some used later widget It's from here , So it can be understood as a UI Component library .
2. Application entry
void main() => runApp(MyApp());
It is the same as most languages ,
FlutterOr saydartyesmainFunction is the entry of the application .mainInvocation in functionrunAppMethod , Its function is to startFlutterapplication .runAppIt accepts aWidgetParametersHow to understand this
WidgetWhat about parameters? ?Just think of it as another name for a component
Or for this entrance , Is and
App.jsx,App.vueA very similar thing
mainThe function usesjsAnonymous function in , This abbreviation is more natural
3. Application structure
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
// apply name
title: 'Flutter Demo',
theme: ThemeData(
// Blue theme
primarySwatch: Colors.blue,
),
// Application home routing
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
MyAppClass representativeFlutterapplication , It inheritedStatelessWidgetclass , that , As a subclass, it is aStatelessWidgetClassSo to put it simply , be-all Widget Are divided into two categories
StatelessWidgetStatefulWidget
In fact, that is
ReactControlled and uncontrolled components in- It's transparent at once, isn't it
that , If analogy
Vueabout
Vue2Pass in
propsTo control is to be controlledChanges in internal data can be understood as controlled , It doesn't need to be like
ReactGo tosetStateOr calluseStataTo update
about
Vue3- Internal data use
refandreactiveThe package is a controlled component
- Internal data use
stay
Flutterin , Almost allwidget, Including somecssThe styles of are all based onwidgetIn the form ofI feel that the style is not pure
cssCome onBut think about it , In this way, the code reads friendly to novices
For beginners ,
FlutterThe style control of should be easier to understand
FlutterWhen building a page , Will call thebuildMethod ,widgetThe main job is to provide abuild()Method- This method is how to build this
widgeComponents
- This method is how to build this
MaterialAppyesMaterial libraryA common foundation provided inWidget, It allows you to set the name of the application , The theme , Language , Home page and route list etc .homeIt's the home page of the app , It is also a what ?widget
home page
1. First time to know Widget
class MyHomePage extends StatefulWidget {
MyHomePage({Key? key, required this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
...
}
Then continue to look up , We App Home page home This widget That is to say MyHomePage It is a controlled component !
Let's talk about the two in detail
1. Controlled , Uncontrolled , A stateful , No state, no more , Simply put, is it responsive , Can you change
2. a key :
Stateful widgetIt consists of at least two classes :StatefulWidgetclassStateclass ,StateWidgetClass itself is immutable , howeverStateThe state held in class iswidgetChanges may occur in the life cycle
2._MyHomePageState Class is MyHomePage Class corresponding state class .
A strange thing
MyHomePageNot in classbuildMethod , Everyone mentioned abovewidgetThere is one. build The method seems differentThis method was moved to
\_MyHomePageStateIn the methodNow let's take a look at the state class
3.State class
a._MyHomePageState Class parsing
below , Let's come to Kangkang, which includes those things !
- State of component
For example, this initialization item is a counter , So the state is a count
int _counter = 0; // Used to record the total number of button clicks
- Set the auto increment function of the State
void _incrementCounter() {
setState(() {
_counter++;
});
}
When the button is clicked , Just call this function , Changing the state will use setState Method , This and React The way in which the aggregation of class components changes state is very similar
hear
FlutterThis method is optimized , There is no need to modify everywidget, The source code has not been understoodstructure
UIInterfacebuildMethodWhen
MyHomePageFirst created ,\_MyHomePageStateClasses will also be created , When initialization is complete ,FlutterThe framework will callwidgetOfbuildMethod to buildwidgetTrees- This and
cssdomTrees , Render a tree
- This and
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text('You have pushed the button this many times:'),
Text(
'$_counter',
style: Theme.of(context).textTheme.headline4,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
ScaffoldyesMaterial libraryPage scaffolding provided in , It provides a default navigation bar , Title and include home screenwidget TreesOfbodyattribute . By default, all routes are throughScaffoldestablishbody Component tree of
It contains a
CenterComponents , It can move sub components to the center of the screen- It's really css Semantically
CenterSelf assembly is aColumn Components, It can arrange all self components in order along the vertical direction of the screenChild components a.Text, Show fixed text
Child components b.Text, Show
\_counterThe number of States
floatingActionButtonIt's the band in the bottom right corner of the page+The button , itsonPressedProperty to accept a callback function , NamelyonClick, ha-haSo the logic is like this
Click button , Call auto increment function
setStateCause page changesrebuildReach a state !!!
b. Why? build Methods on the State What about China? ?
Divide and rule ,
stateAutonomy improves efficiencyState access is convenient
If you put it in
StatefulWidget, That needs to be donestatePass in , It becomes troublesome- Or the
stateState disclosure , But this is verydanger了
- Or the
Come gently , Walk softly
If
buildPut it in there , It will bring trouble to inheritanceThere will be multiple
buildOne mountain cannot tolerate two tigers , Can fight
边栏推荐
- MBA-day28 数的概念-练习题
- Kingbasees SQL language reference manual of Jincang database (8. Function (10))
- Two auxiliary functions of integral Mall for business user operation
- H. Take the elevator greedy
- VS中使用动态库
- 金仓数据库 KingbaseES SQL 语言参考手册 (11. SQL语句:ABORT 到 ALTER INDEX)
- 软件测试面试题全网独家没有之一的资深测试工程师面试题集锦
- 光量子里程碑:6分钟内解决3854个变量问题
- JS的调用方式与执行顺序
- 二叉树的前中后序遍历——本质(每个节点都是“根”节点)
猜你喜欢

Solution to slow download speed of vagrant

NFT in the eyes of blackash: the platform is crying for slaughter, and users send money to the door

Print linked list in reverse order

Lemon class automatic learning after all

Is the transaction in mysql45 isolated or not?

Interview questions for software testing is a collection of interview questions for senior test engineers, which is exclusive to the whole network

【Oracle SQL】计算同比与环比(列转行进行偏移)

Ros2 knowledge: DDS basic knowledge

平衡二叉树(AVL) ~

Unity2d animator cannot create transition
随机推荐
金仓数据库 KingbaseES SQL 语言参考手册 (7. 条件表达式)
leetcode-aboutString
vagrant下载速度慢的解决方法
VS中使用动态库
Autumn move - Preparation Plan
Recursive processing - subproblem
Blurring of unity pixel painting
Modifiers should be declared in the correct order 修饰符应按正确的顺序声明
实习运维知识积累
金仓数据库 KingbaseES SQL 语言参考手册 (8. 函数(十))
中文文本纠错任务简介
[论文笔记] 面向网络语音隐写的抗分组丢失联合编码
Sequential search, half search, block search~
em和rem
[(SV & UVM) knowledge points encountered in written interview] ~ phase mechanism
Kingbasees SQL language reference manual of Jincang database (7. Conditional expression)
金仓数据库 KingbaseES SQL 语言参考手册 (8. 函数(十一))
【(SV && UVM) 笔试面试遇到的知识点】~ phase机制
Mba-day28 concept of number - exercise questions
Kingbasees SQL language reference manual of Jincang database (8. Function (10))