gpt4 book ai didi

dart - 如何从 Switch 调用函数

转载 作者:行者123 更新时间:2023-12-05 01:27:51 26 4
gpt4 key购买 nike

使用在 Android Studio 中创建的默认 Flutter 应用程序,我尝试测试 Switch ,所以我添加了以下代码:

new Switch(value: true, onChanged: (bool newValue) {
setState(() {
_incrementCounter(); // executed only if the value is true
});
},),

incrementCounter 函数是:

  void _incrementCounter() {
setState(() {
_counter++;
});
}

我遇到的问题是,一旦 Switch 值切换回 false,就会调用并执行 incrementCounter 函数,而什么我希望每次切换开关时都应调用 incrementCounter 函数,即无论新值是真还是假!

最佳答案

正如@aziza所说,问题是:

You are not switching the value.

所以这应该可以工作

class MyApp extends StatefulWidget {
@override
MyAppState createState() {
return new MyAppState();
}
}

class MyAppState extends State<MyApp> {
var _value=false;
var inc=0;
onchange(bool value){
setState((){
inc++;
_value=value;
});
}
@override
Widget build(BuildContext context) {
return new Scaffold(
appBar: new AppBar(),
body : new Column(children: <Widget>[
new Switch(value: _value, onChanged: (bool value)=>onchange(value)),
new Center(child: new Text("value ${inc}"),)
],)
);
}
}

enter image description here

关于dart - 如何从 Switch 调用函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49740723/

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