Issue
I’ve ran into problem getting UI lags when this line is running:
var keys = crypt.generateKeys();
Here is the full function:
void createKeys(_) async {
SharedPreferences prefs = await SharedPreferences.getInstance();
var keys = crypt.generateKeys(); // laggy line
prefs.setString('persPriv', keys[0]);
prefs.setString('persPub', keys[1]);
prefs.setString('mesPriv', keys[2]);
prefs.setString('mesPub', keys[3]);
}
I was trying to wrap this function with Isolate
.
Isolate.spawn(createKeys, null);
But I’ve got an error:
[VERBOSE-2:ui_dart_state.cc(199)] Unhandled Exception: Invalid argument(s): Isolate.spawn expects to be passed a static or top-level function
What is the correct way to start isolates to prevent frame drops and UI lagging?
Solution
I don’t believe you can use SharedPreferences within an Isolate without support for MethodChannel / accessing platform-specific underlying OS frameworks on iOS / Android.
You would need to use FlutterIsolate or a similar package to provide that support.
chunhunghan has a good answer detailing this.
Alternatively, you could run the crypt.generateKeys()
by itself in your Isolate.spawn()
call and use the results after in a separate method accessing SharedPreferences
. (Assuming that crypt
package is also not relying on platform-specific code.)
Answered By – Baker
Answer Checked By – David Goodson (FlutterFixes Volunteer)