Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

execute code at library level after class definition in dart

Tags:

dart

So I am trying to migrate a small utility code from JS to Dart and I struggling to find how to do the following:

a registry is used to map Class to a function that is returning a new instance of DifferentClass.

typedef DifferentClass InstanceGenerator();
Map<Type, InstanceGenerator> _registry;
_registry[ClassDefinition] = () => new DifferentClass();

// at runtime
var a = new ClassDefinition();
var b = _registry[a.runtimeType](); // should resolve to instance of DifferentClass.

This all is working fine and well, but the problem I am currently facing is that I need to be able to add to the registry outside of any class's scope and basically at the level of the library. In JS this is implemented as top level call, but in Dart this seem to be not allowed (the DartEditor says NO).

How do I do this pattern in Dart: basically I need to register for each class a function that resolves to an instance of another class and at runtime based on the runtimeType of the instance of the first class create the one registered for it.

Currently it looks like this:

library whatever;
class ABC {}
Registry.instance.register(ABC, () => new DEF()); // This does not work.
like image 534
Peter StJ Avatar asked Sep 13 '25 20:09

Peter StJ


1 Answers

You can't put code to be executed at library top-level. You can only create functions, classes, enums and typedefs at library top-level. In Dart everything needs to be called explicitly from main() or from anything that was invoked from main()

You can create a function like

library whatever;
class ABC {}
register() => Registry.instance.register(ABC, () => new DEF()); 

then for example from main

import 'whatever.dart' as we;

main() {
  we.register();
}

Alternatively you could use the initialize package to do this declarativly.

like image 116
Günter Zöchbauer Avatar answered Sep 16 '25 19:09

Günter Zöchbauer