一、Flutter 中自定义有状态组件
在 Flutter 中自定义组件其实就是一个类,这个类需要继承 StatelessWidget/StatefulWidget。
StatelessWidget 是无状态组件,状态不可变的 widget
StatefulWidget 是有状态组件,持有的状态可能在 widget 生命周期改变。通俗的讲:如果我们想改变页面中的数据的话这个时候就需要用到 StatefulWidget
import 'package:flutter/material.dart';
void main() => runApp(MyApp());
class MyApp extends StatelessWidget {
//Flutter2.2.0 之后需要注意把 Key 改为可空类型 {Key? key} 表示 key 为可空类型
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(title: Text('有状态的组件')),
body: HomePage(),
));
}
}
class HomePage extends StatefulWidget {
//Flutter2.2.0 之后需要注意把 Key 改为可空类型 {Key? key} 表示 key 为可空类型
HomePage({Key? key}) : super(key: key);
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
int count = 0;
@override
Widget build(BuildContext context) {
return Container(
child: Column(
children: <Widget>[
Chip(label: Text("${this.count}")),
RaisedButton(
child: Text('增加'),
onPressed: () {
// print(this.count);
setState(() {
this.count++;
});
},
)
],
));
}
}