Flutter学习之state的使用记录
·
主要是代码的注释
import 'package:flutter/material.dart';
// 继承一个有状态的类
class Counter extends StatefulWidget {
// This class is the configuration for the state.
// It holds the values (in this case nothing) provided
// by the parent and used by the build method of the
// State. Fields in a Widget subclass are always marked
// "final".
// 实例化构造函数
const Counter({super.key});
// 重写
// statefulWedget是一个抽象类,它的内部定义了一个createState方法。
// 现在的Counter类继承自statefulWedget,所以必须重写createState方法,
// 告诉Flutter框架:使用我定义的逻辑来创建状态
// 为什么要使用 @override 呢?
// 这是因为createState方法在statefulWedget类中已经有了一个默认的实现,
// 但是这个默认实现并不适用于我们自定义的Counter组件,所以我们需要重写它,
// 以便提供适合我们组件的状态创建逻辑
// 如果不使用 @override,编译器就不会判断重写的代码部分,
// 如果父类的方法名称写错了,编译器将不会提醒“父类没有这个方法”,
//认为你定义了一个新的方法,从而引发运行时错误
@override
// State<Counter>:这是方法的返回值类型。
//它告诉编译器,这个方法返回的对象必须是专门服务于counter组件的state对象,
//可以删除,但是加上可以增加代码的可读性
// createState():这是方法的名称,表示创建状态对象。
//每当Flutter想要在屏幕上显示Counter组件时,它就会调用这个方法来获取一个状态对象
// => _CounterState():这是方法的实现部分。
//它使用了Dart语言中的箭头函数语法,表示这个方法返回一个_CounterState类的实例。
//_CounterState类是我们为Counter组件定义的状态类,它包含了组件的状态逻辑和UI构建方法
State<Counter>createState() => _CounterState();
}
// _CounterState:在Dart语言中,下划线_代表私有。他只能在当前的.dart文件下被访问。
//因为外界(其他文件)只需要知道Counter这个组件怎么使用,不需要知道它的内部数据是如何变化的,这符合封装的原则。
// extends: 表示继承。继承了Flutter矿建提供的State基类。
//继承了state类,就可以管理生命周期(如initState,dispose)以及最核心的setState()方法。
//没有这个继承,你就无法通知Flitter页面需要刷新。
// <Counter>:泛型参数,这是一种绑定关系,它告诉Flutter这个state是专门为Counter组件服务的。
//通过这种绑定关系,Flutter可以确保在渲染Counter组件时,
// 使用的是对应的_CounterState状态对象,从而正确管理组件的状态和UI更新。
// 通过这个泛型,可以在_CounterState类中访问Counter组件的属性和方法(如果有的话),实现组件和状态之间的交互,
//如:在Counter类中定义了一个配置项final String title;,可以在_CounterState类中通过widget.title来访问这个配置项的值。
class _CounterState extends State<Counter> {
int _counter = 0;
int _eyes = 1;
void _increment() {
setState(() {
// This call to setState tells the Flutter f ramework
// that something has changed in this State, which
// causes it to rerun the build method below so that
// the display can reflect the updated values. If you
// change _counter without calling setState(), then
// the build method won't be called again, and so
// nothing would appear to happen.
_counter++;
_eyes = _eyes*2;
});
}
@override
Widget build(BuildContext context) {
// This method is rerun every time setState is called,
// for instance, as done by the _increment method above.
// The Flutter framework has been optimized to make
// rerunning build methods fast, so that you can just
// rebuild anything that needs updating rather than
// having to individually changes instances of widgets.
return Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
ElevatedButton(onPressed: _increment, child: const Text('Increment')),
const SizedBox(width: 16),
Text('Count: $_counter'),
Text('test:'),
Text('Count: $_eyes'),
],
);
}
}
void main() {
runApp(
const MaterialApp(
home: Scaffold(body: Center(child: Counter())),
),
);
}
更多推荐
所有评论(0)