0 x00 preface
The code for Flutter runs on root ISOLATE by default. Can a Flutter create an ISOLATE itself? Of course you can! Next, we created our own isolate!
0x01 dart:isolate
The code for the ISOLATE is in the isolate.dart file, which contains a method for generating the ISOLATE:
external static Future<Isolate> spawn<T>(
void entryPoint(T message), T message,
{bool paused: false,
bool errorsAreFatal,
SendPort onExit,
SendPort onError});
Copy the code
Spawn method, there are two mandatory parameters, function entryPoint and parameter message, where
-
function
The function must be a top-level function or a static method
-
parameter
The parameter must contain SendPort
0x02 Start writing
The creation steps are written in the comments of the code
import 'dart:async';
import 'dart:io';
import 'dart:isolate';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart'; Void main() async{runApp(MyApp()); void main() async{runApp(MyApp()); //asyncFibonacci creates a ISOLATE and returns the resultprint(await asyncFibonacci(20)); Future<dynamic> asyncFibonacci(int n) async{// Create a ReceivePort first. SendPort needs ReceivePort to create final Response = new ReceivePort(); Spawn function is the code in the ISOLate. dart function. _ISOLATE is a function we implemented ourselves. await Isolate.spawn(_isolate,response.sendPort); // Get sendPort to send data final sendPort = await response.first as sendPort; ReceivePort final answer = new ReceivePort(); Sendport.send ([n, answer.sendport]); // Get data and returnreturnanswer.first; Void _ISOLATE (SendPort initialReplyTo){final port = new ReceivePort(); / / bind initialReplyTo. Send (port. SendPort); // Listen to port.listen((message){final data = message[0] as int; final send = message[1] as SendPort; Send (syncFibonacci(data)); }); } int syncFibonacci(int n){return n < 2 ? n : syncFibonacci(n-2) + syncFibonacci(n-1);
}
Copy the code
0x03 Run Result
Run the program directly and you will see the following print in log:
flutter: 6765
Copy the code
What is 0x04 ISOLATE good for?
Why did you create your own ISOLATE? What’s the use?
Because the Root ISOLATE takes care of rendering and UI interaction, what if we have a time-consuming operation? We know that the ISOLATE is an event loop. If a time-consuming task is running, all subsequent UI operations are blocked, so if we have time-consuming operations, we should put them in the ISOLATE!
Refer to the article
Hackernoon.com/are-futures…