Flutter有无状态类与State及生命周期详细介绍

Flutter中的生命周期类似于Vue、React中的生命周期一样,有初始化、状态更新、停用、销毁等。

在React中,组件分为函数式组件和类式组件,它们的区别就是一个无状态、一个有状态。那么在Flutter中亦是如此,它有两种类,一种是无状态类,一种是有状态类。其生命周期的使用就是有状态类的特定用法。

无状态类

无状态类内部有build方法,在表面上看 每次数据更新都会执行build方法。但实际上,在组件树中,当每次数据发生变更时,无状态类都会重新执行组件LessComponent对象。

class LessComponent extends StatelessWidget {
 const LessComponent({Key? key}) : super(key: key);
 @override
 Widget build(BuildContext context) {
 return Container();
 }
}

有状态类

在有状态类中,每次的数据发生变动,在组件树中只会调用state下的build方法进行重新渲染。这时候就能保存state中的状态。

所谓的状态就是 state里的属性。

class FulComponent extends StatefulWidget {
 const FulComponent({Key? key}) : super(key: key);
 @override
 _FulComponentState createState() => _FulComponentState();
}
class _FulComponentState extends State<FulComponent> {
 @override
 Widget build(BuildContext context) {
 return Container();
 }
}

状态

刚才讲到,状态就是state中的属性值。下面来个示例进行讲解:

class FulComponent extends StatefulWidget {
 const FulComponent({Key? key}) : super(key: key);
 @override
 _FulComponentState createState() => _FulComponentState();
}
class _FulComponentState extends State<FulComponent> {
 int count = 0;
 static const sum = 10;
 final nowDate = new DateTime.now();
 @override
 Widget build(BuildContext context) {
 return Container(
 child: Column(
 children: [
 Text('${sum}'),
 ElevatedButton.icon(
 onPressed: () {
 setState(() {
 count++;
 });
 },
 icon: Icon(Icons.add), 
 label: Text('添加')
 )
 ],
 ),
 );
 }
}

例如 整型值count、常量 sum、当前时间。这都是属于状态值,它们存在的区别就是count可以通过setSatate进行改变。

当每次执行setState()时,此组件都会调用build方法进行将改变的数据进行重新渲染,以此来保证state中的属性值的保存。

State生命周期

class FulComponent extends StatefulWidget {
 const FulComponent({Key? key}) : super(key: key);
 @override
 _FulComponentState createState() => _FulComponentState();
}
class _FulComponentState extends State<FulComponent> {
 int count = 0;
 static const sum = 10;
 final nowDate = new DateTime.now();
 @override
 void initState() { // 初始化生命周期钩子
 super.initState();
 //初始化操作 在这里做
 }
 @override
 void didChangeDependencies() {
 super.didChangeDependencies();
 // 依赖发生变更时 执行
 }
 @override
 void reassemble() {
 super.reassemble();
 // 重新安装时执行,一般在调试的时候用,在发正式版本时 不会执行
 }
 @override
 void didUpdateWidget(covariant FulComponent oldWidget) {
 super.didUpdateWidget(oldWidget);
 // 组件发生变更时调用,当父组件有变动,子组件也会执行此方法
 }
 @override
 void deactivate() {
 super.deactivate();
 // 停用
 }
 @override
 void dispose() {
 super.dispose();
 // 销毁
 }
 @override
 Widget build(BuildContext context) {
 return Container(
 child: Column(
 children: [
 Text('${sum}'),
 ElevatedButton.icon(
 onPressed: () {
 setState(() {
 count++;
 });
 },
 icon: Icon(Icons.add),
 label: Text('添加')
 )
 ],
 ),
 );
 }
}
作者:聂大哥原文地址:https://honker.blog.csdn.net/article/details/124511565

%s 个评论

要回复文章请先登录注册