英文:
Flutter - Unable to use setState() in TextButton
问题
不能在我的所有按钮中使用setState
的原因是,setState
的返回类型是 void
,不能用作 onPressed
的值。要实现您的目标,可以将 setState
包装在一个匿名函数内,如下所示:
TextButton(
style: TextButton.styleFrom(
fixedSize: Size(
MediaQuery.of(context).size.width / 2, 100),
),
onPressed: () {
setState(() {
logPage = false;
});
},
child: const Text(
"Sign Up",
style: TextStyle(fontSize: 20),
),
)
这样,当按钮被点击时,setState
将被调用,从而更新变量 logPage
并重建您的应用程序页面以反映更改。
英文:
Why cannot I use setState in any of my buttons in flutter?
This is my code of the button:
TextButton(
style: TextButton.styleFrom(
fixedSize: Size(
MediaQuery.of(context).size.width / 2, 100),
),
onPressed: setState(() {
logPage = false;
}),
child: const Text(
"Sign Up",
style: TextStyle(fontSize: 20),
),
)
but the setState command is underlined and Android Studio says:
This expression has a type of 'void' so its value can't be used.
I would like to change the variable and rebuild my app page to get it updated and it should show changes.
答案1
得分: 0
onPressed: () => setState(() {
logPage = false;
}),
英文:
Try this:
onPressed: () => setState(() {
logPage = false;
}),
答案2
得分: 0
你在*onPressed:
*的定义中调用了setState()
。你需要提供一个在将来某个时间运行的函数,例如VoidCallback
。它会看起来像这样:
onPressed: () {
setState(() {
logPage = false;
});
}
请注意,*onPressed
*现在是一个函数,而不是调用函数的结果。
英文:
You are invoking setState()
in the definition of your onPressed:
. You need to provide a function to be run at a future time, as in a VoidCallback. It'd look something like:
onPressed: () { setState(() { logPage = false; }),
Notice that the onPressed is now a function, not the result of calling a function.
答案3
得分: 0
尝试清除构建缓存:
flutter clean
然后重新构建。
英文:
Try to clear build cache :
flutter clean
an rebuild again
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论