Flutter的代码都是默认跑在root isolate上的,那么Flutter中能不能本身建立一个isolate呢?固然能够!,接下来咱们就本身建立一个isolate!bash
有关isolate的代码,都在isolate.dart
文件中,里面有一个生成isolate的方法:异步
external static Future<Isolate> spawn<T>(
void entryPoint(T message), T message,
{bool paused: false,
bool errorsAreFatal,
SendPort onExit,
SendPort onError});
复制代码
spawn
方法,必传参数有两个,函数entryPoint和参数message,其中async
函数函数
函数必须是顶级函数或静态方法oop
参数ui
参数里必须包含SendPort
spa
建立的步骤,写在代码的注释里code
import 'dart:async';
import 'dart:io';
import 'dart:isolate';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
//一个普普统统的Flutter应用的入口
//main函数这里有async关键字,是由于建立的isolate是异步的
void main() async{
runApp(MyApp());
//asyncFibonacci函数里会建立一个isolate,并返回运行结果
print(await asyncFibonacci(20));
}
//这里以计算斐波那契数列为例,返回的值是Future,由于是异步的
Future<dynamic> asyncFibonacci(int n) async{
//首先建立一个ReceivePort,为何要建立这个?
//由于建立isolate所需的参数,必需要有SendPort,SendPort须要ReceivePort来建立
final response = new ReceivePort();
//开始建立isolate,Isolate.spawn函数是isolate.dart里的代码,_isolate是咱们本身实现的函数
//_isolate是建立isolate必需要的参数。
await Isolate.spawn(_isolate,response.sendPort);
//获取sendPort来发送数据
final sendPort = await response.first as SendPort;
//接收消息的ReceivePort
final answer = new ReceivePort();
//发送数据
sendPort.send([n,answer.sendPort]);
//得到数据并返回
return answer.first;
}
//建立isolate必需要的参数
void _isolate(SendPort initialReplyTo){
final port = new ReceivePort();
//绑定
initialReplyTo.send(port.sendPort);
//监听
port.listen((message){
//获取数据并解析
final data = message[0] as int;
final send = message[1] as SendPort;
//返回结果
send.send(syncFibonacci(data));
});
}
int syncFibonacci(int n){
return n < 2 ? n : syncFibonacci(n-2) + syncFibonacci(n-1);
}
复制代码
直接运行程序就会在log里看到以下的打印:事件
flutter: 6765
复制代码
说了这么久,为何要建立本身的isolate?有什么用?ci
由于Root isolate会负责渲染,还有UI交互,若是咱们有一个很耗时的操做呢?前面知道isolate里是一个event loop(事件循环),若是一个很耗时的task一直在运行,那么后面的UI操做都被阻塞了,因此若是咱们有耗时的操做,就应该放在isolate里!