群组
Flutter,iOS,Android,Python等,闲聊工作&技术&问题;
个人主页:https://waitwalker.cn
telegram群链接:https://t.me/joinchat/Ej0o0A1ntlq5ZFIMzzO5Pw
当我们用Flutter创建一个空的demo的时候,Flutter会为我们创建一个计数器的Demo.
当点击”+”号时,页面中的数字会递增.而这个功能的实现在lib/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',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0;
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called, for instance as done
// by the _incrementCounter method above.
//
// The Flutter framework has been optimized to make rerunning build methods
// fast, so that you can just rebuild anything that needs updating rather
// than having to individually change instances of widgets.
return Scaffold(
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
// Column is also layout widget. It takes a list of children and
// arranges them vertically. By default, it sizes itself to fit its
// children horizontally, and tries to be as tall as its parent.
//
// Invoke "debug painting" (press "p" in the console, choose the
// "Toggle Debug Paint" action from the Flutter Inspector in Android
// Studio, or the "Toggle Debug Paint" command in Visual Studio Code)
// to see the wireframe for each widget.
//
// Column has various properties to control how it sizes itself and
// how it positions its children. Here we use mainAxisAlignment to
// center the children vertically; the main axis here is the vertical
// axis because Columns are vertical (the cross axis would be
// horizontal).
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
'$_counter',
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
1.依赖包的导入:
import 'package:flutter/material.dart';
将package目录下的flutter环境下的material.dart导入到当前文件.
2.入口函数:
void main() => runApp(MyApp());
和iOS中的程序一样,Flutter也有一个顶级入口函数main()函数,通过”=>”操作符是方法的简写,可以理解为前面方法调用后面方法,这个main()函数内部调用的是runApp(widget)方法,这个方法定义在Binding.dart文件中:
其主要作用是创建并启动Flutter应用,这里传入的是MyApp的实例,MyApp继承自StatelessWidget,StatelessWidget继承自Widget,这里你可以重写main()函数,然后调用runApp()方法:
void main(List<String> args) {
print("this is main method");
}
3.app页面结构
在Flutter中你所能看到的一切都是Widget,甚至其内部调用的Center,Column等都是Widget:
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
这里有一个MaterialApp也是Widget,其功能是帮助构建Flutter应用的框架,通过这个widget你可以设置APP的名称,主题,首页,路由列表等,这里主页home设置是MyHomePage.
4.MyHomePage首页
之前我们说过了,类的构造方法是一个与类同名的函数,MyHomePage的构造方法里面有两个参数key和title,内部定义了一个final修饰的不可变属性title,其值通过类初始化传递.首页由两部分组成:
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, 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) {by
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.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}
一个是继承自StatefulWidget的 MyHomePage,一个是继承自State类的_MyHomePageState类.在MyHomePage中我们看到重写了StatefulWidget类中的createState()方法,这个方法内部调用的是_MyHomePageState()即_MyHomePageState的构造函数,createState()返回的也是_MyHomePageState即State.
继续探究,_MyHomePageState类中重写了build()方法这个方法调用Scaffold实例化方法,返回Scaffold实例,Scaffold可以理解为APP的容器,它包括appBar,body,floatingActionButton等Widget,由它构建了Widget树(也可以称为视图树).
floatingActionButton是那个飘起来的按钮,它接受了一个点击后的回调方法_incrementCounter,这个回调方法内部调用的是setState(() {}方法,当按钮被点击时这个方法被回调,然后计数器数字递增,然后 setState被调用,然后调用build方法,更新页面.
现在我们可以了解页面的刷新时机了:
1)创建state时,也就是createState(),调用build()刷新页面;
2)更新state时,也就是setState()时,也调用build()刷新页面.
5.Flutter APP生命周期
现在总结下来,Flutter 应用的生命周期,借用网上一张图片,可以鲜明看出: