gpt4 book ai didi

dart - 回调函数在 flutter 中不起作用

转载 作者:IT王子 更新时间:2023-10-29 07:10:08 25 4
gpt4 key购买 nike

创建示例以了解 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())),
),
),
],
),
);
}
}

最佳答案

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

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

关于dart - 回调函数在 flutter 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51323114/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com