Create an instance of an object from a String in Dart? Create an instance of an object from a String in Dart? dart dart

Create an instance of an object from a String in Dart?


The Dart code:

ClassMirror c = reflectClass(MyClass);InstanceMirror im = c.newInstance(const Symbol(''), ['MyAttributeValue']);var o = im.reflectee;

Learn more from this doc: http://www.dartlang.org/articles/reflection-with-mirrors/

(From Gilad Bracha)


Using built_mirrors you can do it next way:

library my_lib;import 'package:built_mirrors/built_mirrors.dart';part 'my_lib.g.dart';@reflectableclass MyClass {  String myAttribute;  MyClass(this.myAttribute);}main() {  _initMirrors();  ClassMirror cm = reflectType(MyClass);  var o = cm.constructors[''](['MyAttributeValue']);  print("o.myAttribute: ${o.myattribute}");}


This was an issue that has plagued me until I figured that I could implement a crude from method to handle the conversion of encoded Json Objects/strings or Dart Maps to the desired class.

Below is a simple example that also handles nulls and accepts JSON (as the string parameter)

import 'dart:convert';class PaymentDetail{  String AccountNumber;  double Amount;  int ChargeTypeID;  String CustomerNames;  PaymentDetail({    this.AccountNumber,    this.Amount,    this.ChargeTypeID,    this.CustomerNames  });  PaymentDetail from ({ string : String, object : Map  }) {     var map   = (object==null) ? (string==null) ? Map() : json.decode(string) : (object==null) ? Map() : object;     return new PaymentDetail(        AccountNumber             : map["AccountNumber"] as String,        Amount                    : map["Amount"] as double,        ChargeTypeID              : map["ChargeTypeID"] as int,        CustomerNames             : map["CustomerNames"] as String     );  }}

Below is it's implementation

 PaymentDetail payDetail =  new PaymentDetail().from(object: new Map()); PaymentDetail otherPayDetail =  new PaymentDetail().from(object: {"AccountNumber": "1234", "Amount": 567.2980908});

Once again, this is simplistic and tedious to clone throughout the project but it works for simple cases.