Flutter – 无法在 TextButton 中使用 setState()

huangapple go评论108阅读模式
英文:

Flutter - Unable to use setState() in TextButton

问题

不能在我的所有按钮中使用setState的原因是,setState 的返回类型是 void,不能用作 onPressed 的值。要实现您的目标,可以将 setState 包装在一个匿名函数内,如下所示:

  1. TextButton(
  2. style: TextButton.styleFrom(
  3. fixedSize: Size(
  4. MediaQuery.of(context).size.width / 2, 100),
  5. ),
  6. onPressed: () {
  7. setState(() {
  8. logPage = false;
  9. });
  10. },
  11. child: const Text(
  12. "Sign Up",
  13. style: TextStyle(fontSize: 20),
  14. ),
  15. )

这样,当按钮被点击时,setState 将被调用,从而更新变量 logPage 并重建您的应用程序页面以反映更改。

英文:

Why cannot I use setState in any of my buttons in flutter?
This is my code of the button:

  1. TextButton(
  2. style: TextButton.styleFrom(
  3. fixedSize: Size(
  4. MediaQuery.of(context).size.width / 2, 100),
  5. ),
  6. onPressed: setState(() {
  7. logPage = false;
  8. }),
  9. child: const Text(
  10. "Sign Up",
  11. style: TextStyle(fontSize: 20),
  12. ),
  13. )

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

  1. onPressed: () => setState(() {
  2. logPage = false;
  3. }),
英文:

Try this:

  1. onPressed: () => setState(() {
  2. logPage = false;
  3. }),

答案2

得分: 0

你在*onPressed:*的定义中调用了setState()。你需要提供一个在将来某个时间运行的函数,例如VoidCallback。它会看起来像这样:

  1. onPressed: () {
  2. setState(() {
  3. logPage = false;
  4. });
  5. }

请注意,*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:

  1. onPressed: () { setState(() { logPage = false; }),

Notice that the onPressed is now a function, not the result of calling a function.

答案3

得分: 0

尝试清除构建缓存:

  1. flutter clean

然后重新构建。

英文:

Try to clear build cache :

  1. flutter clean

an rebuild again

huangapple
  • 本文由 发表于 2023年3月4日 03:11:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/75631011.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定