Cap1 简介
Flutter
新建组件有俩种状态组件:StatelessWidget
和StatefulWidget
,这些在新建Flutter
项目就能看到相关展示代码,下面就详细解释下这俩者区别:
StatefulWidget
:是指有状态变化的组件,例如系统提供的 Checkbox, Radio, Slider, InkWell, Form, and TextField 都是 stateful widgets, 他们都是 StatefulWidget的子类。
StatelessWidget
:是指没有内部状态变化的组件,例如 Icon、 IconButton, 和Text 都是无状态widget, 他们都是 StatelessWidget的子类。
stateful组件就是和用户交互后会有状态变化,例如滚动条Slider。
stateless组件就是交互后没有状态变化,例如显示的一个文本Text。
Cap2 自定义状态管理组件
stateful组件:
- 创建一个继承自
StatefulWidget
的类来表示你要自定义的可变控件 - 创建一个继承自
State
的类来处理这个可变控件的状态和显示样式(build方法)。 - 当用户交互发生,例如
onPressed
点击事件被触发时,可以调用setState
方法告诉组件需要重绘。
/*
switchBoxFul 是自身widget管理自己状态
*/
class switchBoxFul extends StatefulWidget {
@override
_SwitchBoxState createState() {
return new _SwitchBoxState();
}
}
Flutter
中定义Stateful
类必须返回一个State
类的对象,所以这里定义了一个叫_SwitchBoxState
的state
类,这个类名前面加了下划线 _ 代表这个是私有的类。
class _SwitchBoxState extends State<switchBoxFul> {
bool _switchActive = false; // 按钮显示`关闭`这个状态
void _switchActiveChanged() {
setState(() {
_switchActive = !(_switchActive);
});
}
@override
Widget build(BuildContext context) {
return new GestureDetector(
onTap: _switchActiveChanged,
child: new Center(
child: new Container(
alignment: Alignment.center,
width: 200.0,
height: 200.0,
child: new Text(
_switchActive ? '开' : '关',
style: new TextStyle(fontSize: 50.0, color: Colors.white),
),
decoration: new BoxDecoration(
color: _switchActive ? Colors.green[400] : Colors.grey),
),
),
);
}
}
用_switchActiveChanged()
方法来处理状态的变化,里面用setState
方法告诉组件需要重绘,里面将状态的值可以修改。
无状态管理组件:
其实上面的案例就完全足够了,但在无状态管理组件下如何实现状态管理呢?可以在组件外面一层套入状态管理组件(父类组件)就行了,最终结果实现的效果这俩者没有任何区别,不过这样代码维护比较麻烦一下,下面代码就不再详述了:
/*
SwitchBoxLess 是父widget管理子widget状态;
SwitchBoxLess 继承自无状态控件,不管理任何状态
*/
class SwitchBoxLessWidget extends StatelessWidget {
SwitchBoxLessWidget({Key key, this.switchActive: false, this.onChanged}) : super(key: key);
final switchActive;
final ValueChanged<bool> onChanged;
void _switchActiveChanged() {
onChanged(!switchActive);
}
@override
Widget build(BuildContext context) {
return new GestureDetector(
onTap: _switchActiveChanged,
child: new Center(
child: new Container(
alignment: Alignment.center,
width: 200.0,
height: 200.0,
child: new Text(
switchActive ? '开启' : '关闭',
style: new TextStyle(fontSize: 50.0, color: Colors.white),
),
decoration: new BoxDecoration(
color: switchActive ? Colors.blue : Colors.red),
),
),
);
}
}
/*
ParentWidget类是SwitchBoxLess的父类
他会得知盒子是否被点击从而管理盒子的状态,通过setState更新展示内容
*/
class switchBoxLess extends StatefulWidget {
@override
_SwitchBoxLessState createState() {
return new _SwitchBoxLessState();
}
}
class _SwitchBoxLessState extends State<switchBoxLess> {
bool _switchActive = false;
void _handleSwitchBoxLessChanged(bool value) {
setState(() {
_switchActive = value;
});
}
@override
Widget build(BuildContext context) {
return new SwitchBoxLessWidget(
switchActive: _switchActive,
onChanged: _handleSwitchBoxLessChanged,
);
}
}
代码展示的效果可以在我编写的App
布局里展示。
