回调功能无法正常使用

时间:2018-07-13 10:30:20

标签: dart flutter

创建一个示例来学习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 个答案:

答案 0 :(得分:2)

删除increaseCount()中的括号,因为使用该括号您正在创建VoidCallback的实例,并且该实例只能运行一次,因此请尝试

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

答案 1 :(得分:1)

您应提供increaseCountonPressed回调的引用。

在这里,您将increaseCount()(复选括号)分配给首先调用increaseCount()函数的回调,其返回值将分配给onPressed。这就是为什么它在热重装时仅增加一次的原因。

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