gpt4 book ai didi

flutter - 从匿名函数返回值

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

当我使用匿名函数时。

它显示了编译错误,
Error: A value of type 'Text Function()' can't be assigned to a variable of type 'Widget'.

Widget cols = Column(
children: <Widget>[
((){
if (myFlg){
return Text("OK");
}else {
return Text("No");
}
}),
Text("left"),
Text("Right")
]
);

好,我明白了。
它返回函数本身,而不是 Text() Widget。

但是,在这种情况下,如何从匿名函数返回Text()呢?

最佳答案

您的代码几乎可以正常工作。您忘了执行功能:

(() {
if (myFlg) {
return Text("OK");
} else {
return Text("No");
}
})(),

请注意,您实际上可以将if语句放入集合中,因此在此示例中,您可以避免使用匿名函数并执行以下操作:
Widget cols = Column(
children: <Widget>[
if (myFlg) Text("OK") else Text("No"),
Text("left"),
Text("Right")
]
);

关于flutter - 从匿名函数返回值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59142173/

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