import 'package:flutter/material.dart';
void main() {
runApp(new MyApp());
}
// MyApp 不需要做状态处理 , 所以此组件继承 StatelessWidget 即可
class MyApp extends StatelessWidget {
// 这个组件是整个应用的主组件
@override
Widget build(BuildContext context) {
return new MaterialApp(
title: 'flutter demo',
theme: new ThemeData(
// 自定义主题
primaryColor: Colors.blue,
),
home: new MyHomePage(
title: 'my app title',
),
);
}
}
// 主页需要继承自 StatefulWidget
class MyHomePage extends StatefulWidget {
final String title;
MyHomePage({Key key, this.title}) : super(key: key);
// 必须重写 createState 方法
_MyHomePageState createState() => new _MyHomePageState();
}
// 状态类必须继承 State 类, 注意后面需要指定为 <MyHomePage>
class _MyHomePageState extends State<MyHomePage> {
int _counter = 0; // 计数器
void _incrementCounter() {
// 调用 State 类里的 setState 方法来更改状态值, 使得计数器 +1
setState(() {
_counter++;
});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(
title: new Text(widget.title),
),
body: new Center(
// 居中布局
child: new Column(
// 垂直布局
mainAxisAlignment: MainAxisAlignment.center, // 主轴居中对齐
children: <Widget>[
new Text(
'点击次数 : ',
),
new Text(
'$_counter', // 绑定计数器的值
style: Theme.of(context).textTheme.display1,
),
],
),
),
floatingActionButton: new FloatingActionButton(
onPressed: _incrementCounter, // 按下+号按钮调用自增函数
tooltip: 'Increment',
child: new Icon(Icons.add),
),
);
}
}
Flutter之StatelessWidget和StatefulWidget
最新推荐文章于 2024-05-06 09:30:19 发布