如果你对 State 已经有所了解,可以继续往下看:
在有交互的属性的widget中,调用 setState()
是至关重要的,因为这告诉框架, widget 的状态已经改变,应该重绘。
例如:IconButton
:onPressed()方法等
那么谁管理着 stateful widget 的状态?widget 本身?父 widget?双方?另一个对象?
如何决定使用哪种管理方法?以下原则可以帮助您决定:
-
如果状态是用户数据,如复选框的选中状态、滑块的位置,则该状态最好由父 widget 管理。
-
如果所讨论的状态是有关界面外观效果的,例如动画,那么状态最好由 widget 本身来管理。
如果有疑问,首选是在父 widget 中管理状态。
一、widget 管理自己的状态
顾名思义,本身的状态自己管理。比如:管理自身的数据、样式等。
1.1 示例
知识点:
Text:data是可以动态变化的;
onTap:提取构造方法,可以使界面布局与逻辑关系分开,即符合MVc的模型与视图分离;
BoxDecoration:Widget的装饰,使其改变其显示形式。
import 'package:flutter/material.dart';
// TapboxA manages its own state.
//------------------------- TapboxA ----------------------------------
void main(){
runApp(const MyApp());
}
class TapboxA extends StatefulWidget {
const TapboxA({Key? key}) : super(key: key);
@override
_TapboxAState createState() => _TapboxAState();
}
class _TapboxAState extends State<TapboxA> {
bool _active = false;
void _handleTap() {
setState(() {
_active = !_active;
});
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: _handleTap,
child: Container(
child: Center(
child: Text(
_active ? 'Active' : 'Inactive',
style: const TextStyle(fontSize: 32.0, color: Colors.white),
),
),
width: 200.0,
height: 200.0,
decoration: BoxDecoration(
color: _active ? Colors.lightGreen[700] : Colors.grey[600],
),
),
);
}
}
//------------------------- MyApp ----------------------------------
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: Scaffold(
appBar: AppBar(
title: const Text('Flutter Demo'),
),
body: const Center(
child: TapboxA(),
),
),
);
}
}
BoxDecoration的参数如下:
属性 | 解释 | 类型 |
---|---|---|
color | 颜色背景 | Color |
image | 图片背景 | DecorationImage |
border | 边界 | BoxBorder |
borderRadius | 圆角边界半径 | BorderRadiusGeometry |
boxShadow | 阴影 | List<BoxShadow> |
gradient | 渐变色 | Gradient |
backgroundBlendMode | 背景混合模式 | BlendMode |
shape | 形状 | BoxShape |
1.2 BoxDecoration属性详细示例
自己一定要详细编码,对各个属性了如指掌
import 'package:flutter/material.dart';
// TapboxA manages its own state.
//------------------------- TapboxA ----------------------------------
void main() {
runApp(const MyApp());
}
class TapboxA extends StatefulWidget {
const TapboxA({Key? key}) : super(key: key);
@override
_TapboxAState createState() => _TapboxAState();
}
class _TapboxAState extends State<TapboxA> {
bool _active = false;
void _handleTap() {
setState(() {
_active = !_active;
});
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: _handleTap,
child: Container(
//Cannot provide both a color and a decoration.
// color: Colors.black,
child: Row(
children: [
Container(
child: Center(
child: Text(
_active ? 'Active' : 'Inactive',
style: const TextStyle(fontSize: 32.0, color: Colors.white),
),
),
width: 200.0,
height: 200.0,
decoration: BoxDecoration(
color: _active ? Colors.lightGreen[700] : Colors.grey[600],
),
),
Container(
child: Center(
child: Text(
_active ? 'Active' : 'Inactive',
style: const TextStyle(fontSize: 32.0, color: Colors.white),
),
),
width: 200.0,
height: 200.0,
decoration: BoxDecoration(
//若是设置了 image,color也就无效了
color: _active ? Colors.lightGreen[700] : Colors.grey[600],
image: const DecorationImage(
image: NetworkImage(
'https://flutter.github.io/assets-for-api-docs/assets/widgets/owl-2.jpg'),
fit: BoxFit.cover,
),
border: Border.all(
color: Colors.blueAccent,
width: 8,
),
borderRadius: BorderRadius.circular(12),
),
),
Container(
child: Center(
child: Text(
_active ? 'Active' : 'Inactive',
style: const TextStyle(fontSize: 32.0, color: Colors.white),
),
),
width: 200.0,
height: 200.0,
decoration: BoxDecoration(
//若是设置了gradient,color也就无效了
color: _active ? Colors.lightGreen[700] : Colors.grey[600],
gradient: const LinearGradient(
colors: [Colors.lightBlueAccent, Colors.blueAccent],
begin: Alignment.topCenter,
end: Alignment.bottomCenter,
),
),
)
],
)),
);
}
}
//------------------------- MyApp ----------------------------------
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: Scaffold(
appBar: AppBar(
title: const Text('Flutter Demo'),
),
body: const Center(
child: TapboxA(),
),
),
);
}
}
二、由父widget管理state
一般来说父 widget 管理状态并告诉其子 widget 何时更新通常是最合适的。
IconButton
是一个无状态 widget,因为我们认为父 widget 需要知道该按钮是否被点击来采取相应的处理。这与安卓非常不一样,需要透过示例仔细、再仔细理解。
以下示例,便是将布局元素做了拆分,统一由父类管理。但有时候不必如此繁琐,我们就要因地制宜,混搭管理state。
知识点1:
final ValueChanged<bool> onChanged;
回调函数应用,定义了一个参数为bool类型的回调函数。
知识点2:
const TapboxB({ Key? key, this.active = false, required this.onChanged, }) : super(key: key);
这里相当于自定了一个组合控件(相当于安卓listview中自定义item),后面我们扩展开来将。
import 'package:flutter/material.dart';
// ParentWidget manages the state for TapboxB.
void main() {
runApp(const MyApp());
}
//------------------------ ParentWidget --------------------------------
class ParentWidget extends StatefulWidget {
const ParentWidget({Key? key}) : super(key: key);
@override
_ParentWidgetState createState() => _ParentWidgetState();
}
class _ParentWidgetState extends State<ParentWidget> {
bool _active = false;
void _handleTapboxChanged(bool newValue) {
setState(() {
_active = newValue;
});
}
@override
Widget build(BuildContext context) {
return SizedBox(
child: TapboxB(
active: _active,
onChanged: _handleTapboxChanged,
),
);
}
}
//------------------------- TapboxB ----------------------------------
class TapboxB extends StatelessWidget {
const TapboxB({
Key? key,
this.active = false,
required this.onChanged,
}) : super(key: key);
final bool active;
final ValueChanged<bool> onChanged;
void _handleTap() {
onChanged(!active);
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: _handleTap,
child: Container(
child: Center(
child: Text(
active ? 'Active' : 'Inactive',
style: const TextStyle(fontSize: 32.0, color: Colors.white),
),
),
width: 200.0,
height: 200.0,
decoration: BoxDecoration(
color: active ? Colors.lightGreen[700] : Colors.grey[600],
),
),
);
}
}
//------------------------- MyApp ----------------------------------
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: Scaffold(
appBar: AppBar(
title: const Text('Flutter Demo'),
),
body: const Center(
child: ParentWidget(),
),
),
);
}
}
三、混合管理
父类管理背景,自身管理边框。
import 'package:flutter/material.dart';
void main() {
runApp(const MyApp());
}
//---------------------------- ParentWidget ----------------------------
class ParentWidget extends StatefulWidget {
const ParentWidget({Key? key}) : super(key: key);
@override
_ParentWidgetState createState() => _ParentWidgetState();
}
class _ParentWidgetState extends State<ParentWidget> {
bool _active = false;
void _handleTapboxChanged(bool newValue) {
setState(() {
_active = newValue;
});
}
@override
Widget build(BuildContext context) {
return SizedBox(
child: TapboxC(
active: _active,
onChanged: _handleTapboxChanged,
),
);
}
}
//----------------------------- TapboxC ------------------------------
class TapboxC extends StatefulWidget {
const TapboxC({
Key? key,
this.active = false,
required this.onChanged,
}) : super(key: key);
final bool active;
final ValueChanged<bool> onChanged;
@override
_TapboxCState createState() => _TapboxCState();
}
class _TapboxCState extends State<TapboxC> {
bool _highlight = false;
void _handleTapDown(TapDownDetails details) {
setState(() {
_highlight = true;
});
}
void _handleTapUp(TapUpDetails details) {
setState(() {
_highlight = false;
});
}
void _handleTapCancel() {
setState(() {
_highlight = false;
});
}
void _handleTap() {
widget.onChanged(!widget.active);
}
@override
Widget build(BuildContext context) {
// This example adds a green border on tap down.
// On tap up, the square changes to the opposite state.
return GestureDetector(
onTapDown: _handleTapDown, // Handle the tap events in the order that
onTapUp: _handleTapUp, // they occur: down, up, tap, cancel
onTap: _handleTap,
onTapCancel: _handleTapCancel,
child: Container(
child: Center(
child: Text(widget.active ? 'Active' : 'Inactive',
style: const TextStyle(fontSize: 32.0, color: Colors.white)),
),
width: 200.0,
height: 200.0,
decoration: BoxDecoration(
color: widget.active ? Colors.lightGreen[700] : Colors.grey[600],
border: _highlight
? Border.all(
color: Colors.teal[700]!,
width: 10.0,
)
: null,
),
),
);
}
}
//------------------------- MyApp ----------------------------------
class MyApp extends StatelessWidget {
const MyApp({Key? key}) : super(key: key);
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
home: Scaffold(
appBar: AppBar(
title: const Text('Flutter Demo'),
),
body: const Center(
child: ParentWidget(),
),
),
);
}
}