dart - 回调函数在颤动中不起作用
问题描述
创建一个示例来学习Flutter
. 增加a的counter onTap是一个简单的程序GestureDetetor
但是,回调方法不起作用。热重载时计数会增加,但点击时不会增加。下面是带有注释的代码。
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
这将只运行一次,所以试试这个
return BoxWidget(onPressed: increaseCount, counter: _counter,);
推荐阅读
- reactjs - 反应本机中的反应导航卸载问题
- java - 一个虚拟盒子上的几个类似的Java程序
- php - Laravel 批处理队列导致 MySQL 错误
- google-data-studio - google data-studio 社区可视化是否可以访问我的数据?
- c# - FackItEasy:如何访问传递给伪造接口的参数值?
- haskell - 有没有办法使用类名作为常用数据类型的名称?
- xcode - 如何在 Xcode 的 Interface Builder 中设置 Document Outline 的默认宽度
- python - 无法使用 ctrl + c 终止多处理程序
- python - 将 Tkinter 输入框转换为字符串的解决方法
- java - 是否存在可以“最终确定”对象的私有状态的 Java 方法?