本文介绍了Flutter-在进程之间停止FutureBuilder操作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

重建小部件时如何取消 FutureBuilder 操作

How do I cancel FutureBuilder operation when rebuilding the widget

让我们说我有一个这样的代码...每次我按Floating按钮时,小部件都会重新生成调用 myFuture 的代码,该代码将等待五秒钟,然后计数器递增...现在,我希望在如果我按下Floating按钮五秒钟,则当前的Future(仍处于延迟状态)应停止其运行,新的Future将被调用...因此,最后我应该得到一个计数器2,但我得到3 ...

Lets say I have a code like this... Every time i pressed the Floating button the widget rebuilds calling myFuture which waits five seconds and then the counter increments... Now I want that during that five seconds if I pressed the Floating button the current Future (which is still is delayed) should stop its operation and the new Future will be called...So at the end I should get a counter of 2 but instead I get 3...

class MyHomePage extends StatefulWidget {

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  var counter = 0;
  
  myFuture()async{
    await Future.delayed(Duration(seconds:5));
    counter++;
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(),
      body: FutureBuilder(
        future: myFuture(),
        builder: (context, snapshot) {
          if (snapshot.connectionState == ConnectionState.waiting)
            return Center(child: CircularProgressIndicator());
          else return Text(counter.toString());
        }
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: ()=>setState(() {}),
        child: Icon(Icons.add),
      ),
    );
  }
}
 

推荐答案

要取消Future,您可以使用 async 包中的 CancelableOperation .

In order to cancel a Future, you can use the CancelableOperation from the async package.

其实现如下所示:

  Future<dynamic> executeCancelable(Future<dynamic> futureMethod) async {
    operation?.cancel();
    operation = CancelableOperation.fromFuture(futureMethod, onCancel: () {
      print('Future stopped');
    });

    return operation.value;
  }

  Future<dynamic> futureMethod() async {
    return Future.delayed(const Duration(milliseconds: 3000), () {
      return counter++;
    });
  }

可以通过以下方法调用:

Which can be called with the following method :

executeCancelable(futureMethod())

请注意,在此示例中,我使用的是Future.被取消为在此处解释.
例如,此代码片段可以很好地与API查询配合使用.

Note that in this example, I'm using a Future.delayed wich can't "really" be cancelled as explained here.
This snippet would work well with an API query for example.

这篇关于Flutter-在进程之间停止FutureBuilder操作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-27 12:53