android - 为什么计数器变量的值在屏幕上没有变化?

标签 android flutter

我添加了一个 float 操作按钮和一个增加计数器变量值的增量函数,它在 float 按钮的 onressed 函数中调用。该值在控制台上发生变化,但在我的应用程序上没有变化。你能给我一个解决方案吗?

Widget build(BuildContext context) {
    int counter = 0;
   void incrementCounter() {
      counter++;
      print("You have pressed the button $counter times.");
    }
    return new Scaffold( 
       body: new Center(
          child: new Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              new Text("You have pressed the button $counter times.")
            ],
          ),
        ),
      floatingActionButton: new FloatingActionButton(
        onPressed: incrementCounter,
        child: new Icon(Icons.send),
      )
    );
   }

第 5 行在控制台上工作,但第 13 行在我的应用程序上不工作,计数器仅为 0。我添加的代码刚好足以让您理解它。 ;)

最佳答案

每次重新渲染小部件时,您都将计数器重置为 0,并且您不使用 setState() 更新状态,因此 Flutter 不会重新- 当值改变时渲染。

改成

int counter = 0;
void incrementCounter() {
  setState(() => counter++);
  print("You have pressed the button $counter times.");
}

Widget build(BuildContext context) {
    return new Scaffold( 
       body: new Center(
          child: new Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              new Text("You have pressed the button $counter times.")
            ],
          ),
        ),
      floatingActionButton: new FloatingActionButton(
        onPressed: incrementCounter,
        child: new Icon(Icons.send),
      )
    );
   }

关于android - 为什么计数器变量的值在屏幕上没有变化?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54341050/

相关文章:

android - 无法解析 : com. facebook.fresco :fresco:0. 8.1+

java - 蓝牙条码getInputStream()

java - android.view.InflateException 由 : java. lang.OutOfMemoryError 引起

Flutter webrtc无法设置远程应答sdp

Flutter - 墨水池 : Why does onHover() require onTap()?

java - 可运行处理程序未在 fragment 内执行。无法启动可运行的

android - android模拟器不启动,avd

list - API工作正常,但返回类名的实例

Flutter Google 登录 - 此应用程序未验证错误

flutter - 如何在 Flutter 中用作边框颜色的两种颜色之间连续设置动画