gpt4 book ai didi

flutter - 何时在flutter中使用Valuechanged <>与Valuesetter <>

转载 作者:行者123 更新时间:2023-12-03 03:14:32 24 4
gpt4 key购买 nike

我一直在他们网站上关注一些初学者入门教程,并且正在为基本交互性进行this教程,特别是使用父窗口小部件管理子窗口小部件状态的部分。有一个ParentWidget_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,
),
);
}
}
TapboxBParentWidget的子类,其代码如下:
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],
),
),
);
}
}
单击小部件时,将调用 _handleTap方法,该方法将调用 onChanged回调,该回调将切换 active变量。在 onChanged的定义中,类型为 ValueChanged<bool>,它被记录为“报告基础值已更改的回调的签名”。如果我将其更改为 ValueSetter<bool>,则该应用程序将以完全相同的方式工作,并且似乎没有任何变化。所以我的问题是这两者之间有什么区别?在这种特定情况下更好吗?

最佳答案

我仅使用Flutter ValueChanged ValueSetter为您搜索了文档,并迅速找到this:

void ValueSetter (T Value)

Signature for callbacks that report that a value has been set.

This is the same signature as ValueChanged, but is used when the callback is called even if the underlying value has not changed. For example, service extensions use this callback because they call the callback whenever the extension is called with a value, regardless of whether the given value is new or not.

typedef ValueSetter<T> = void Function(T value);


因此,它们只是相同基础类型的typedef,但是具有不同的语义,尽管具有相同基础签名,但仍可以用作自文档代码。
如果您不需要 ValueSetter的后一含义,请使用 ValueChanged,如API所述。

关于flutter - 何时在flutter中使用Valuechanged <>与Valuesetter <>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62799446/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com