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


Posted in Java/Android onApril 07, 2022

使用异步包(推荐)

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的资料请关注三水点靠木其它相关文章!

Java/Android 相关文章推荐
Jackson 反序列化时实现大小写不敏感设置
Jun 29 Java/Android
Java实现房屋出租系统详解
Oct 05 Java/Android
springboot如何接收application/x-www-form-urlencoded类型的请求
Nov 02 Java/Android
SSM项目使用拦截器实现登录验证功能
Jan 22 Java/Android
关于ObjectUtils.isEmpty() 和 null 的区别
Feb 28 Java/Android
RestTemplate如何通过HTTP Basic Auth认证示例说明
Mar 17 Java/Android
Java中的继承、多态以及封装
Apr 11 Java/Android
引用计数法和root搜索算法以及JVM中判定对象需要回收的方法
Apr 19 Java/Android
Ubuntu18.04下QT开发Android无法连接设备问题解决实现
Jun 01 Java/Android
java实现自定义时钟并实现走时功能
Jun 21 Java/Android
Java Spring Boot请求方式与请求映射过程分析
Jun 25 Java/Android
springboot 全局异常处理和统一响应对象的处理方式
Jun 28 Java/Android
java如何实现获取客户端ip地址的示例代码
Apr 07 #Java/Android
Android Flutter实现3D动画效果示例详解
Apr 07 #Java/Android
Android Flutter实现图片滑动切换效果
MyBatis配置文件解析与MyBatis实例演示
Java 深入探究讲解简单工厂模式
springboot用户数据修改的详细实现
Apr 06 #Java/Android
Java中API的使用方法详情
You might like
世界收音机发展史
2021/03/01 无线电
一个php作的文本留言本的例子(一)
2006/10/09 PHP
有关 PHP 和 MySQL 时区的一点总结
2008/03/26 PHP
PHP PDOStatement::setFetchMode讲解
2019/02/03 PHP
JavaScript 入门基础知识 想学习js的朋友可以参考下
2009/12/26 Javascript
jquery 全局AJAX事件使用代码
2010/11/05 Javascript
Jquery获得控件值的三种方法总结
2014/02/13 Javascript
js实现通用的微信分享组件示例
2014/03/10 Javascript
Jquery搜索父元素操作方法
2015/02/10 Javascript
JavaScript面对国际化编程时的一些建议
2015/06/24 Javascript
jQuery超精致图片轮播幻灯片特效代码分享
2015/09/10 Javascript
Bootstrap modal使用及点击外部不消失的解决方法
2016/12/13 Javascript
JS 调试中常见的报错问题解决方法
2017/05/20 Javascript
uniapp电商小程序实现订单30分钟倒计时
2020/11/01 Javascript
[02:27]刀塔重生降临
2015/10/14 DOTA
Python的Twisted框架上手前所必须了解的异步编程思想
2016/05/25 Python
利用Python开发实现简单的记事本
2016/11/15 Python
Tensorflow简单验证码识别应用
2017/05/25 Python
python+matplotlib实现鼠标移动三角形高亮及索引显示
2018/01/15 Python
Python多线程中阻塞(join)与锁(Lock)使用误区解析
2018/04/27 Python
python实现从文件中读取数据并绘制成 x y 轴图形的方法
2018/10/14 Python
对python添加模块路径的三种方法总结
2018/10/16 Python
使用python制作游戏下载进度条的代码(程序说明见注释)
2019/10/24 Python
Python利用全连接神经网络求解MNIST问题详解
2020/01/14 Python
Python configparser模块操作代码实例
2020/06/08 Python
详解FireFox下Canvas使用图像合成绘制SVG的Bug
2019/07/10 HTML / CSS
Html5 new XMLHttpRequest()监听附件上传进度
2021/01/14 HTML / CSS
求职简历中的自我评价分享
2013/12/08 职场文书
售后服务承诺书模板
2014/05/21 职场文书
本科应届生求职信
2014/08/05 职场文书
公安个人四风问题对照检查及整改措施
2014/10/28 职场文书
2015年学雷锋活动总结
2015/02/06 职场文书
2015年妇女工作总结
2015/05/14 职场文书
2015年社区国庆节活动总结
2015/07/30 职场文书
汶川大地震感悟
2015/08/10 职场文书
《狮子和鹿》教学反思
2016/02/16 职场文书