Flutter异步编程详解

// 耗时操作的方法:bigCompute

Future bigCompute(int initalNumber) async {

int total = initalNumber;

for (var i = 0; i < 1000000000; i++) {

total += i;

}

return total;

}

// 点击按钮调用的方法:calculator

void calculator() async {

int result = await bigCompute(0);

print(result);

}

// FloatingActionButton的点击事件

FloatingActionButton(

onPressed: calculator,

tooltip: ‘Increment’,

child: Icon(Icons.add),

)

  • 修改代码
  1. 新建一个calculatorByComputeFunction方法,用compute调用bigCompute方法:

void calculatorByComputeFunction() async {

// 使用compute调用bigCompute方法,传参0

int result = await compute(bigCompute, 0);

print(result);

}

  1. 修改FloatingActionButton的点击事件方法为calculatorByComputeFunction

FloatingActionButton(

onPressed: calculatorByComputeFunction,

tooltip: ‘Increment’,

child: Icon(Icons.add),

)

咱点击试试?

[VERBOSE-2:ui_dart_state.cc(186)] Unhandled Exception: Invalid argument(s): Illegal argument in isolate message : (object is a closure - Function ‘bigCompute’:.)

  1. 解决Error:将bigCompute改为为static方法(改为全局函数也是可行的)

static Future bigCompute(int initalNumber) async {

int total = initalNumber;

for (var i = 0; i < 1000000000; i++) {

total += i;

}

return total;

}

警告:还有一个需要注意的是所有的Platform-Channel的通信必须在Main Isolate中执行,譬如在其他Isolate中调用rootBundle.loadString("assets/***")就掉坑里了。

2. 直接使用Isolate

上面我们用compute方法,基本上没有看到Isolate的身影,因为Flutter帮我们做了很多工作,包括Isolate创建,销毁,方法的执行等等。一般情况下我们使用这个方法就够了。

但是这个方法有个缺陷,我们只能执行一个任务,当我们有多个类似的耗时操作时候,如果使用这个compute方法将会出现大量的创建和销毁,是一个高消耗的过程,如果能复用Isolate那就是最好的实现方式了。

多线程Isolate间通信的原理如下:

  1. 当前Isolate接收其他Isolate消息的实现逻辑: Isolate之间是通过Port进行通信的,ReceivePort是接收器,它配套有一个SendPort发送器, 当前Isolate可以把SendPort发送器送给其他Isolate,其他Isolate通过这个SendPort发送器就可以发送消息给当前Isolate了。

  2. 当前

你可能感兴趣的:(程序员,flutter)