Home > Software design >  Dart Factory class for creating variables with type
Dart Factory class for creating variables with type

Time:12-25

The problem is the following. I had a typescript factory class that I attempted to do in Dart:

class FactoryClass{

  factory FactoryClass(dynamic types, String className, dynamic defaultValue){
    if(types[className] != null ){
      return types[className](defaultValue);
    }
    else{
      throw Exception("");
    }
  }
}

In TS it was used like this:

let variable= new FactoryClass([String, Number, etc...], "Number", "42")

That in TypeScript would give back a Number type variable with the value 42

However, it's not gonna work in Dart since types have no constructor for this. So I can't do something like

final myString = new String("def_value")

So the question arises, how can I go about it in dart?

CodePudding user response:

You can do similar in Dart with just functions:

typedef Factory = dynamic Function(dynamic value);

dynamic create(Map<String, Factory> types, String className, dynamic defaultValue) {
    if (types.containsKey(className)) {
      return types[className]!(defaultValue);
    } else {
      throw Exception("no factory for $className");
    }
  }

final factories = <String,  Factory>{
  'String': (s) => s.toString(),
  'int': (i) => i is int ? i : int.parse('$i'),
  'bool': (b) => b is bool ? b : ('$b' == 'true'),
};

show(v) => print('Value $v has type ${v.runtimeType}');

main() {
  show(create(factories, 'String', 'foo'));
  show(create(factories, 'int', '42'));
  show(create(factories, 'bool', 'false'));
}

Prints:

Value foo has type String
Value 42 has type int
Value false has type bool
  • Related