程序的入口
只需要在runApp中传入Widget就可以了:
void main() => runApp(MyApp());
MyApp
- StatelessWidget:无状态Widget
- build方法:用于构建一个Widget
- MaterialApp:相当于定义一个App的大体结构,将显示的内容(home属性)和全局配置(标题、主题等)分开
- MyHomePage:页面内容Widget
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'),
);
}
}
MyHomePage
看几个关键点:
- StatefulWidget:有状态的Widget,可以理解为内容可变
- createState方法:因为是有状态的,重写这个方法,创建属于自己的State
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
final String title;
@override
_MyHomePageState createState() => _MyHomePageState();
}
_MyHomePageState
关键的地方:
- 继承State<MyHomePage>:这个泛型的意思就是说这个State的宿主是谁,State是提供给谁用的。可以通过widget拿到MyHomePage实例,比如:widget.title
- setState()方法:修改state方法,与React Native的setState相似
- Scaffold Widget:Scaffold 是一个Material Design风格的框架。Scaffold已经定义好appBar、body等内容的位置,我们只需要在这里属性中传入Widget。
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.display1,
),
],
),
),
floatingActionButton: FloatingActionButton(
onPressed: _incrementCounter,
tooltip: 'Increment',
child: Icon(Icons.add),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}