Home > Net >  Dart using variable to hold set of constructor parameters, to be used in multiple constructors?
Dart using variable to hold set of constructor parameters, to be used in multiple constructors?

Time:01-23

is there a way to use some variable or any holder to store constructor parameters, to be able to pass them to multiple constructors without repeating the values?

I think its possible if the constructor has only positional parameters (no named parameters).

var parametersHolder={
named1: "str",
named2: "lorem",
};


// normal usage
constructorA(named1: "str", named2: "lorem");

constructorB(named2: "lorem",named1: "str" );

my question is how to do the following in dart:

constructorA(parametersHolder);

constructorB(parametersHolder);

so is that achievable ?

Thanks

CodePudding user response:

You can define a class to hold your parameters like this:

class MyClass{
  late final int myInt;
  late final String myString;
  
  MyClass.firstConstructor(MyClassParams params){
    this.myInt = params.myInt;
    this.myString = params.myString;
  }
  
  MyClass.secondConstructor(MyClassParams params){
    this.myInt = params.myInt;
    this.myString = params.myString;
  }
}


class MyClassParams{
  final int myInt;
  final String myString;
  
  const MyClassParams(this.myInt, this.myString);
}

CodePudding user response:

If you really want, you could use Function.apply with a constructor tear-off:

class Foo {
  String named1;
  String named2;
  
  Foo({required this.named1, required this.named2});
  
  @override
  String toString() => 'Foo: $named1 $named2';
}

void main() {
  var namedArguments = {
    #named1: 'str',
    #named2: 'lorem',
  };
  
  var foo = Function.apply(Foo.new, null, namedArguments) as Foo;
  print(foo); // Prints: Foo: str lorem
}

Note that doing this sacrifices compile-time type-safety.

  • Related