首页 文章

回调功能无法振作

提问于
浏览
0

创建一个示例来学习Flutter中的回调。这是一个简单的程序来增加GestureDetetor的计数器 onTap 但是,回调方法不起作用。热重载时计数增加但未点击。以下是带注释的代码。

class BoxState extends State<ChangeBoxState>{
  int _counter = 0;

  //Callback method changes the state onTap of GestureDetector widget. It is not calling onTap.
  increaseCount(){
    setState(() {
      ++_counter;
      print(_counter);
    });
  }

  @override
  Widget build(BuildContext context) {
    // Passing the callback method,"increaseCount()" to stateless class where GestureDetector is defined.
    return BoxWidget(onPressed: increaseCount(), counter: _counter,);
  }

}

无国籍班级:

class BoxWidget extends StatelessWidget{

  BoxWidget({this.onPressed, this.counter});

  final VoidCallback onPressed;
  final int counter;

  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return Container(
      decoration: BoxDecoration(color: Colors.blue[500]),
      child: Column(
        children: <Widget>[Center(child: Text('Hello, world!')),
        GestureDetector(
          onTap: onPressed, //Passing onPressed to onTap.

          child: Container(
            margin: const EdgeInsets.only(left:0.0, top:200.0, right:0.0, bottom:0.0),
            height: 200.0,
            width: 200.0,
            decoration: BoxDecoration(
              color: Colors.teal[200],
              border: Border.all(color: Colors.yellow, width: 10.0, style: BorderStyle.solid),
              borderRadius: BorderRadius.all(Radius.circular(20.0)),
            ),
            child: Center(child: Text(counter.toString())),
          ),
        ),
        ],
      ),
    );
  }
}

2 回答

  • 2

    删除increaseCount()中的括号,因为使用您正在创建VoidCallback实例的括号,这将只运行一次,所以试试这个

    return BoxWidget(onPressed: increaseCount, counter: _counter,);
    
  • 1

    您应该为onPressed回调提供increaseCount的引用。

    在这里,您将increaseCount()(检查大括号)分配给首先调用increaseCount()函数的回调,并将其返回值分配给onPressed。这就是为什么它只在热重载上增加一次。

    return BoxWidget(onPressed: increaseCount, counter: _counter,);
    

相关问题