gpt4 book ai didi

Flutter:如何取消任务

转载 作者:IT王子 更新时间:2023-10-29 06:33:58 24 4
gpt4 key购买 nike

我有一个按钮,单击它会进行计算,如果再次按下该按钮,如果计算未完成,计算应该停止。我怎样才能在这里取消执行_doCalc?

class _MyHomePageState extends State<MyHomePage> {

bool _calculating = false;

void _doCalc() async {
_setCalculating(true);
// do some calculation
...
_setCalculating(false);

}

void _setCalculating(bool calculating) {
setState(() {
_calculating = calculating;

});
}

@override
Widget build(BuildContext context) {

mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new RaisedButton(
child: Text(_calculating ? "Stop" : "Start"),
onPressed: () {

if (_calculating) {
_setCalculating(false);

// stop execution of _doCalc() ????

} else {
_doCalc();
}
},
),
],
}
}
}

最佳答案

你可以玩一些标志,比如这个例子:

class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
bool _calculating = false;
bool inProgress = false;

_doCalc() async {
// do some calculation
if (inProgress){
inProgress = false;
_setCalculating(false);
return;
}
inProgress = true;
_setCalculating(true);
await yourOperation();
if (inProgress){
inProgress = false;
print("DISPLAY YOUR RESULT using setState");
_setCalculating(false);
return;
} else {
print("don't display because it was cancelled");
_setCalculating(false);
}

}

Future yourOperation() {
return Future.delayed(Duration(seconds: 3));
}

void _setCalculating(bool calculating) {
setState(() {
_calculating = calculating;
});
}

@override
Widget build(BuildContext context) {
return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
new RaisedButton(
child: Text(_calculating ? "Stop" : "Start"),
onPressed: () {
_doCalc();
},
),
]);
}
}

关于Flutter:如何取消任务,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51777531/

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