-
StatelessWidget 是无状态组件,状态不可变的 Widget
-
StatefulWidget 是有状态组件,持有的状态可能在 widget 生命周期改变。通俗的讲:如果我们想改变页面中的数据的话这个时候就需要用到 StatefulWidget
-
StatelessWidget的例子
import 'package:flutter/material.dart';
main() {
runApp(MyApp());
}
//MaterialApp组件作为根组件使用
// Scaffold 有下面几个主要属性
// appBar-界面顶部导航栏 body-界面显示的主要内容Widget drawer-抽屉菜单控件
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
// TODO: implement buildå
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('导航栏'),
),
body: HomePage(),
),
);
}
}
class HomePage extends StatelessWidget {
int countNum = 1;
//自动生成的常量构造函数
//变量必须是常量,否则就注释常量构造函数
// const HomePage({Key key}) : super(key: key);
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
SizedBox(height: 200),
Text('${this.countNum}'),
SizedBox(height: 50),
RaisedButton(
child: Text('刷新+1'),
onPressed: () {
this.countNum++;
print(this.countNum);
},
),
],
);
}
}
- StateflulWidget组件
import 'package:flutter/material.dart';
main() {
runApp(MyApp());
}
//MaterialApp组件作为根组件使用
// Scaffold 有下面几个主要属性
// appBar-界面顶部导航栏 body-界面显示的主要内容Widget drawer-抽屉菜单控件
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
// TODO: implement buildå
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('导航栏'),
),
body: HomePage(),
),
);
}
}
class HomePage extends StatefulWidget {
HomePage({Key key}) : super(key: key);
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int countNum = 1;
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
SizedBox(height: 200),
Text('${this.countNum}'),
SizedBox(height: 50),
RaisedButton(
child: Text('刷新+1'),
onPressed: () {
setState(() {
this.countNum++;
print(this.countNum);
});
},
),
],
);
}
}
网友评论