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

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

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

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:

确定