我一直在关注他们网站上的一些初学者颤振教程,并且正在编写本教程以实现基本的交互性,特别是使用父窗口小部件来管理子窗口小部件的状态的部分。有一个ParentWidget
and_ParentWidgetState
类,其代码如下:
class ParentWidget extends StatefulWidget {
@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 Container(
child: TapboxB(
active: _active,
onChanged: _handleTapboxChanged,
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
TapboxB
是 的子类ParentWidget
,其代码如下:
class TapboxB extends StatelessWidget {
TapboxB({this.active: false, @required this.onChanged});
final bool active;
final ValueChanged<bool> onChanged;
void _handleTap() {
onChanged(!active);
}
Widget build(BuildContext context) {
return GestureDetector(
onTap: _handleTap,
child: Container(
child: Column(
//aligns column in the centre vertically
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text(
//sets text depending on _active boolean
active ? 'Active' : 'Inactive',
style: TextStyle(fontSize: 20.0, color: Colors.white),
),
Text(
'Tapbox B',
style: TextStyle(fontSize: 14.0, color: Colors.white),
),
],
),
width: 100.0,
height: 100.0,
decoration: BoxDecoration(
//sets colour depending on _active boolean
color: active ? Colors.lightGreen[700] : Colors.grey[600],
),
),
);
}
}
Run Code Online (Sandbox Code Playgroud)
_handleTap
单击小部件时会调用该方法,该方法会调用onChanged
回调,从而切换active
变量。onChanged
在类型的定义中,ValueChanged<bool>
它被记录为“报告基础值已更改的回调的签名”。但是,如果我对此进行更改,ValueSetter<bool>
应用程序将以完全相同的方式工作,并且似乎没有任何变化。所以我的问题是这两者有什么区别?在这种特定情况下,有更好的方法吗?
und*_*e_d 13
我使用flutter ValueChanged ValueSetter搜索了文档,发现了这个:
void ValueSetter (T Value)
报告值已设置的回调签名。
这与 ValueChanged 的签名相同,但在调用回调时使用,即使底层值没有更改。例如,服务扩展使用此回调,因为每当使用值调用扩展时,无论给定值是否是新值,它们都会调用回调。
typedef ValueSetter<T> = void Function(T value);
因此,它们只是相同底层类型的 typedef,但具有不同的语义含义,尽管底层签名相同,但可能用作自文档代码。
如果您不需要 的后一个含义ValueSetter
,则使用ValueChanged
, 正如 API 所说。
归档时间: |
|
查看次数: |
14855 次 |
最近记录: |