How can I dynamically construct a Dart script for spawnUri?
Asked Answered
B

1

11

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.

Booby answered 26/5, 2015 at 17:43 Comment(0)
B
16

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.

Booby answered 26/5, 2015 at 17:43 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.