[Flutter/dart] How to use flutter_isolate
Overview
You may want to run heavy processing on a different isolate to make the operation lighter. Basically, you can use the compute() method, but you cannot use the compute() method in the case of processing that uses the code specific to each platform of android and ios. Specific examples are processes such as creating local_notification and acquiring location information. It seems that messages cannot be sent via platform channel from other than main isolate. (reference)
Then, in such a case, there is no such thing as giving up. If you use a library called flutter_isolate, you can process with another isolate.
How to use
Add the following to pubsec.yaml and install the library
dependencies:
flutter_isolate: ^1.0.0+14
import library
import 'package:flutter_isolate/flutter_isolate.dart';
Define heavy processing (simple function for explanation, but actually processing using platform channel)
static Future<void> heavy_method(int num) async{
//some heavy processing
}
It should be noted here that the method must be static and that it can only take one primitive type argument, such as an int or string. If you want to take multiple arguments or instance members as arguments, pass them in json format. (See previous article)
Pass the heavy method as the first argument of FlutterIsolate.spawn () and the argument of that method as the second argument.
final isolate=await FlutterIsolate.spawn(heavy_method, 1);
Only this! Really easy!
Lastly
Flutter_isolate itself is easy to use, so the hard part is to unify the method arguments. Especially when using platform channel, there are many elements to use, and it may be difficult if it needs third-party variables.
In my case, it was a process of creating a lot of notifications with local_notification, but I made as many variables as possible static and did it in another isolate.
Recent Posts
See AllWhat want to do I want to create an input form using TextField. For example, if the input content is a monetary amount, I would like to...
What want to do There is a variable that remain unchanged once the initial value is determined. However, it cannot be determined yet when...
What want to do As the title suggests. Place two widgets in one line on the screen One in the center of the screen and the other on the...
Bình luận