详解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 相关文章推荐
Java并发编程必备之Future机制
Jun 30 Java/Android
Springboot配置suffix指定mvc视图的后缀方法
Jul 03 Java/Android
spring cloud gateway中如何读取请求参数
Jul 15 Java/Android
看完这篇文章获得一些java if优化技巧
Jul 15 Java/Android
spring boot中nativeQuery的用法
Jul 26 Java/Android
mybatis中注解与xml配置的对应关系和对比分析
Aug 04 Java/Android
Java SSM配置文件案例详解
Aug 30 Java/Android
springboot新建项目pom.xml文件第一行报错的解决
Jan 18 Java/Android
java后台调用接口及处理跨域问题的解决
Mar 24 Java/Android
springboot读取nacos配置文件
May 20 Java/Android
Spring IOC容器Bean的作用域及生命周期实例
May 30 Java/Android
Android基础入门之dataBinding的简单使用教程
Jun 21 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
全国FM电台频率大全 - 10 江苏省
2020/03/11 无线电
PHP文件操作实例总结【文件上传、下载、分页】
2018/12/08 PHP
模拟select的代码
2011/10/19 Javascript
基于jquery的文章中所有图片width大小批量设置方法
2013/08/01 Javascript
Js判断参数(String,Array,Object)是否为undefined或者值为空
2013/11/04 Javascript
JS判断网页广告是否被浏览器拦截过滤的代码
2015/04/05 Javascript
JavaScript实现仿网易通行证表单验证
2015/05/25 Javascript
JS实现的表格操作类详解(添加,删除,排序,上移,下移)
2015/12/22 Javascript
深入理解Vue transition源码分析
2017/07/30 Javascript
vue动画效果实现方法示例
2019/03/18 Javascript
微信小程序--获取用户地理位置名称(无须用户授权)的方法
2019/04/29 Javascript
微信小程序实现收货地址左滑删除
2020/11/18 Javascript
vue实现全匹配搜索列表内容
2019/09/26 Javascript
[03:08]Ti4观战指南上
2014/07/07 DOTA
python通过pil模块获得图片exif信息的方法
2015/03/16 Python
python将ip地址转换成整数的方法
2015/03/17 Python
python使用BeautifulSoup分页网页中超链接的方法
2015/04/04 Python
python学习数据结构实例代码
2015/05/11 Python
Python提取网页中超链接的方法
2016/09/18 Python
Django密码存储策略分析
2020/01/09 Python
详解pandas获取Dataframe元素值的几种方法
2020/06/14 Python
Django生成数据库及添加用户报错解决方案
2020/10/09 Python
python中zip()函数遍历多个列表方法
2021/02/18 Python
天鹅的故事教学反思
2014/02/04 职场文书
园艺师求职信
2014/03/10 职场文书
家长给学校的建议书
2014/05/15 职场文书
计划生育证明书写要求
2014/09/17 职场文书
论文答谢词
2015/01/20 职场文书
顶岗实习协议书
2015/01/29 职场文书
品质保证书格式
2015/02/28 职场文书
观看建国大业观后感
2015/06/01 职场文书
2015年工商局个人工作总结
2015/07/23 职场文书
学会感恩主题班会
2015/08/12 职场文书
商业计划书如何写?关键问题有哪些?
2019/07/11 职场文书
Python编解码问题及文本文件处理方法详解
2021/06/20 Python
2022微信温控新功能上线
2022/05/09 数码科技