I have a button which when clicked does a calculation, and if the button is pressed again the calculation should stop if it is not finished. How can I cancel the execution of _doCalc here?
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();
}
},
),
],
}
}
}
You can play with some flags, like this example:
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();
},
),
]);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With