c/c++语言开发共享详解Flutter和Dart取消Future的三种方法

使用异步包(推荐)async包由 dart 编程语言的作者开发和发布。它提供了dart:async风格的实用程序来增强异步计算。可以帮助我们取消future的是cancelableoperation类

使用异步包(推荐)

async包由 dart 编程语言的作者开发和发布。它提供了dart:async风格的实用程序来增强异步计算。可以帮助我们取消future的是cancelableoperation类:

var mycancelablefuture = cancelableoperation.fromfuture(    future<t> inner,     { futureor oncancel()? }  )  ​  // call the cancel() method to cancel the future  mycancelablefuture.cancel();

为了更清楚,请参阅下面的实际示例。

完整示例

应用预览

详解Flutter和Dart取消Future的三种方法

我们要构建的应用程序有一个浮动按钮。按下此按钮时,将开始异步操作(这需要 5 秒才能完成)。按钮的背景从靛蓝变为红色,其标签从“开始”变为“取消”,现在您可以使用它来取消future。

  • 如果您在future完成前 5 秒内点击取消按钮,屏幕将显示“future已被取消”。
  • 如果您什么都不做,则 5 秒后屏幕将显示“future completed”。

一个演示价值超过一千字:

代码

1.通过执行以下操作安装异步包:

flutter pub add async

然后运行:

flutter pub get

2.main.dart 中的完整源代码(附解释):

// main.dart  import 'package:flutter/material.dart';  import 'package:async/async.dart';  ​  void main() {    runapp(const myapp());  }  ​  class myapp extends statelesswidget {    const myapp({key? key}) : super(key: key);    @override    widget build(buildcontext context) {      return materialapp(          // remove the debug banner          debugshowcheckedmodebanner: false,          title: '大前端之旅',          theme: themedata(            primaryswatch: colors.indigo,          ),          home: const homepage());    }  }  ​  class homepage extends statefulwidget {    const homepage({key? key}) : super(key: key);  ​    @override    _homepagestate createstate() => _homepagestate();  }  ​  class _homepagestate extends state<homepage> {    // this future will return some text once it completes    future<string?> _myfuture() async {      await future.delayed(const duration(seconds: 5));      return 'future completed';    }  ​    // keep a reference to cancelableoperation    cancelableoperation? _mycancelablefuture;  ​    // this is the result returned by the future    string? _text;  ​    // help you know whether the app is "loading" or not    bool _isloading = false;  ​    // this function is called when the "start" button is pressed    void _getdata() async {      setstate(() {        _isloading = true;      });  ​      _mycancelablefuture = cancelableoperation.fromfuture(        _myfuture(),        oncancel: () => 'future has been canceld',      );      final value = await _mycancelablefuture?.value;  ​      // update the ui      setstate(() {        _text = value;        _isloading = false;      });    }  ​    // this function is called when the "cancel" button is tapped    void _cancelfuture() async {      final result = await _mycancelablefuture?.cancel();      setstate(() {        _text = result;        _isloading = false;      });    }  ​    @override    widget build(buildcontext context) {      return scaffold(        appbar: appbar(title: const text('大前端之旅')),        body: center(          child: _isloading              ? const circularprogressindicator()              : text(                  _text ?? 'press start button',                  style: const textstyle(fontsize: 28),                ),        ),        // this button is used to trigger _getdate() and _cancelfuture() functions        // the function is called depends on the _isloading variable        floatingactionbutton: elevatedbutton(          onpressed: () => _isloading ? _cancelfuture() : _getdata(),          child: text(_isloading ? 'cancel' : 'start'),          style: elevatedbutton.stylefrom(              padding: const edgeinsets.symmetric(vertical: 20, horizontal: 30),              primary: _isloading ? colors.red : colors.indigo),        ),      );    }  }

使用 timeout() 方法

这种方法既快速又简单。但是,它不是很灵活。

使用timeout()方法,您可以限制future的时间(例如 3 秒)。如果 future 及时完成,它的值将被返回。另一方面,如果future超过限制时间,将执行ontimeout函数:

future<t> timeout(     duration timelimit,    {futureor<t> ontimeout()?}  )

快速示例

创建一个虚拟的future:

future<string?> _myfuture() async {      await future.delayed(const duration(seconds: 10));      return 'future completed';  }

设置超时 3 秒:

_myfuture().timeout(        const duration(seconds: 3),        ontimeout: () =>            'the process took too much time to finish. please try again later',  );

将future转换为流

您可以使用 future 类的asstream()方法来创建一个包含原始future结果的流。现在您可以取消对该流的订阅。

快速示例

// don't forget to import this  import 'dart:async';  ​  // create a demo future  future<dynamic> _loaddata() async {      await future.delayed(const duration(seconds: 10));      return 'some data';  }  ​  // a reference to the stream subscription  // so that we can call _sub.cancel() later  streamsubscription<dynamic>? _sub;  ​  // convert the future to a stream  _sub = _loaddata().asstream().listen((data) {      // do something with "data"      print(data);   });  ​  // cancel the stream subscription  _sub.cancel();

请注意,这个快速示例仅简要描述了事物的工作原理。您必须对其进行修改以使其可在现有项目中运行。

结论

你已经学会了不止一种方法来取消 flutter 中的future。从其中选择一个以在您的应用程序中实现,以使其在处理异步任务时更加健壮和吸引人。

以上就是详解flutter和dart取消future的三种方法的详细内容,更多关于flutter dart取消future的资料请关注<计算机技术网(www.ctvol.com)!!>其它相关文章!

需要了解更多c/c++开发分享详解Flutter和Dart取消Future的三种方法,都可以关注C/C++技术分享栏目—计算机技术网(www.ctvol.com)!

本文来自网络收集,不代表计算机技术网立场,如涉及侵权请联系管理员删除。

ctvol管理联系方式QQ:251552304

本文章地址:https://www.ctvol.com/c-cdevelopment/1073956.html

(0)
上一篇 2022年4月7日
下一篇 2022年4月7日

精彩推荐