【Flutter】一文搞懂异步编程

本文深入探讨了Flutter中的异步编程,包括事件循环机制、Future的创建与使用、FutureBuilder组件、Stream和StreamBuilder组件的详细讲解。通过示例展示了Future如何注册回调、Async与Await的配合使用,以及Stream的持续输出特性。
摘要由CSDN通过智能技术生成

1 事件循环机制(Event Loop)

Flutter中异步操作不是多线程,与Java不同。

程序无响应原因:
①计算量过大;
②等待操作。

多线程(Multithreading):耗时操作时,新建线程进行操作,渲染 UI 的主线程就不会被挂起引起卡顿。
在这里插入图片描述
Isolate(隔离):Dart 中的线程,但又与线程不同,是微线程或协程。与线程的区别是不能共享内存,同时也不存在锁竞争的问题。 每个Isolate都是独立的执行线,有自己的事件循环,只能通过发送消息进行通信,所以资源开销低于线程。
在这里插入图片描述
在实际项目中不需要是Isolate来创建线程,使用单个线程本身的事件循环。

事件循环机制:保证 main() 中代码不断循环,不会运行一下就结束。主要操作就是检查 Event Queue 中的事件并执行,所以异步操作就是向 Event Queue 中添加事件。
只要Microtask中还存在事件就要执行 Microtask ,执行完后才能执行 Event Queue中的事件
在这里插入图片描述
向 Event Queue 中添加事件:

void main() {
   
	//在事件队列中添加打印A事件
	Future(
		() => print("A"));
	//执行完打印B后检查事件队列
	print("B");
}

输出结果:先打印B后打印A

向 Microtask Queue 中添加事件:

void main() {
   
	scheduleMicrotask(
		() => print("A"));
	print("B");
}

在实际项目中不会特别使用 Microtask Queue

总结:
①直接运行

Future.sync()
Future.value()

_.then()

②Microtask

scheduleMicrotask()
Future.microtask()

_conpleted.then()

③Event

Future()
Future.delayed()

2 Future详解

示例:

http.get(url).then((value) => null).catchError(onError);

2.1 创建Future

立即执行Future.sync();
最后执行Future();

void main() {
   

  Future.delayed(Duration(seconds: 1), () => print("Future 3"));
  Future(() => print("Future 1"));
  Future.delayed(Duration.zero, () => print("Future 2"));//Duration.zero是否存在按照语句顺序执行
  
  scheduleMicrotask(() => print("microtask 1"));
  Future.microtask(() => print("microtask 2"));
  Future.value(123).then((value) => print("microtask 3"));

  print("main 1");
  Future.sync(() => print("sync"));
  Future.value(getName());//直接返回结果
  print("main 2");


  runApp(MyApp());
}

String getName() {
   
  print("Future value");
  return "Future value";
}

查看打印结果:

I/flutter (19131): main 1
I/flutter (19131): sync
I/flutter (19131): Future value
I/flutter (19131): main 2
I/flutter (19131): microtask 1
I/flutter (19131): microtask 2
I/flutter (19131): microtask 3
I/flutter (19131): Future 1
I/flutter (19131): Future 2
I/flutter (19131): Future 3 //等待1s后打印

then()的使用:

void main() {
   

  Future.delayed(Duration(seconds: 1), () => print("delayed"))
      .then((value) {
   
        scheduleMicrotask(() => print("micro"));
        print("then 1");
      })
      .then((value) => print
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值