Flutter 中自定义有状态组件
在 Flutter 中自定义组件其实就是一个类,这个类需要继承StatelessWidget/StatefulWidget。
StatelessWidget 是无状态组件,状态不可变的 widget。
StatefulWidget 是有状态组件,持有的状态可能在 widget 生命周期改变。通俗的讲:如果我
们想改变页面中的数据的话这个时候就需要用到 StatefulWidget。
练习:
点击按钮,使数字+1
class HomePage extends StatefulWidget {
final int countNum=0;
const HomePage({
Key? key}) : super(key: key);
@override
State<HomePage> createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int countNum=0;
@override
Widget build(BuildContext context) {
return Column(
children: [
SizedBox(height: 200,),
Chip(label: Text('${this.countNum}')),
SizedBox(height: 20,),
ElevatedButton(
onPressed: (){
setState(() {
this.countNum++;
});
},
child: Text('按钮'))
],
);
}
}
练习2:
class _HomePageState extends State<HomePage> {
List list = [];
@override
Widget build(BuildContext context) {
return ListView(
children: [
Column(
children: this
.list
.map((e) => ListTile(
title: Text(e), ///易错点,注意,listTile中的title是一个组件,不是字符串
))
.toList()),
SizedBox(height: 20,),
ElevatedButton(onPressed: () {
setState(() {
this.list.add('新增数据1');
this.list.add('新增数据2');
});
}, child: Text('按钮'))
],
);
}
}