How can I dynamically construct a Dart script for spawnUri?

Issue

I want to dynamically construct and load a Dart script. How do I do this?

I know I can use Isolate.spawnUri to dynamically load a Dart script. However, I’m only aware that I can load from file: and http: URIs. This means I need to put my script somewhere to be loaded, which is a complication I’d like to avoid.

Solution

In Dart SDK 1.10, you can now create a data: URI from a String, and pass that data: URI to spawnUri.

This means you can dynamically construct a string, at runtime, encode it, and dynamically load/run it. Neat!

Here’s an example.

Your Dart script:

import 'dart:isolate';

main() {
  var loadMe = '''

main() {
  print('from isolate');
}

''';

  var uri = Uri.parse('data:application/dart;charset=utf-8,${Uri.encodeComponent(loadMe)}');
  print('loading $uri');

  Isolate.spawnUri(uri, null, null);
}

Notice the data: URI must be of the form:

data:application/dart;charset=utf-8,DATA

where DATA is URI percent encoded.

Also, utf-8 must be lower case.

Answered By – Seth Ladd

Answer Checked By – Katrina (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *