Dynamic Instantiate in Dart

Issue

I need an object that makes instances of other objects. I want the ability to pass in the class of the objects being created, but they all need to have the same type, and it would be great if they could all start out with the same values:

class Cloner{

  BaseType prototype;

  BaseType getAnother(){
    BaseType newthing = prototype.clone(); //but there's no clone() in Dart
    newthing.callsomeBaseTypeMethod();
    return newthing;
  }
}

So, prototype could be set to any object that is of type BaseClass, even if it’s something whose class is a subclass of BaseClass. I’m sure there’s a way to do this with the mirrors library, but I just wanted to make sure I’m not missing some obvious built-in factory way to do it.

I could see how this could be set up with a generic: Cloner<T>, but then there’s no way that we can make sure T is a subtype of BaseType at compile-time, right?

Solution

To get you started, you can create a small “constructor” function that returns new instances. Try this:

typedef BaseType Builder();

class Cloner {
  Builder builder;

  Cloner(Builder builder);

  BaseType getAnother() {
    BaseType newthing = builder();
    newthing.callsomeBaseTypeMethod();
    return newthing;
  }
}

main() {
  var cloner = new Cloner(() => new BaseType());
  var thing = cloner.getAnother();
}

In the above code, we create a typedef to define a function that returns a BaseType.

Answered By – Seth Ladd

Answer Checked By – Timothy Miller (FlutterFixes Admin)

Leave a Reply

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