Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter: How to cancel a task

Tags:

flutter

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();
            }
          },
        ),
      ],
    }
  }
}
like image 893
tmath Avatar asked Oct 28 '22 07:10

tmath


1 Answers

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();
            },
          ),
        ]);
  }
}
like image 155
diegoveloper Avatar answered Nov 15 '22 08:11

diegoveloper