回调功能无法正常使用 [英] Callback function not working in flutter

查看:58
本文介绍了回调功能无法正常使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

创建一个示例来学习 Flutter 中的回调.这是一个简单的程序,可以增加 GestureDetetor 的onTap计数器,但是回调方法不起作用.热装时计数增加,但丝锥未增加.下面是带有注释的代码.

Creating an example to learn callbacks in Flutter. It's a simple programme to increase the counter onTap of a GestureDetetor But, the callback method is not working. The count increase on hot reload but not on tap. Below is the code with comments.

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())),
          ),
        ),
        ],
      ),
    );
  }
}

推荐答案

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

remove the the bracket in increaseCount() because using the bracket you are creating an instance of your VoidCallback and this will run one time only so try this

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

这篇关于回调功能无法正常使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆