Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a named constructor from a generic function in Dart/Flutter

Tags:

I want to be able to construct an object from inside a generic function. I tried the following:

abstract class Interface
{
  Interface.func(int x);
}
class Test implements Interface
{
  Test.func(int x){}
}
T make<T extends Interface>(int x)
{
  // the next line doesn't work
  return T.func(x);
}

However, this doesn't work. And I get the following error message: The method 'func' isn't defined for the class 'Type'.

Note: I cannot use mirrors because I'm using dart with flutter.

like image 557
Ameen Avatar asked Mar 19 '19 09:03

Ameen


People also ask

How do you call a constructor in flutter?

Factory Constructor in Dart/Flutter We can use the factory keyword for a constructor that return an object instead of creating a new instance. class Customer { String name; int age; String location; static final Customer origin = Customer("", 0, ""); // factory constructor factory Customer.

How do you use generics in Dart?

Dart supports the use of generic types (often denoted as T ) in three general places: In a function's arguments. In local variables inside a function. In a function's return type.

How do you make a constructor private in Dart?

A constructor can be made private by using (_) underscore operator which means private in dart. The same theory applied while extending class also, It's also impossible to call the private constructor if it declares in a separate file.

What is the use of named constructor in Dart?

Named constructors in DartGiving your constructors different names allows your class to have many constructors and also to better represent their use cases outside of the class. The constructor withoutABS initializes the instance variable hasABS to false, before the constructor body executes.


1 Answers

Dart does not support instantiating from a generic type parameter. It doesn't matter if you want to use a named or default constructor (T() also does not work).

There is probably a way to do that on the server, where dart:mirrors (reflection) is available (not tried myself yet), but not in Flutter or the browser.

You would need to maintain a map of types to factory functions

void main() async {
  final double abc = 1.4;
  int x = abc.toInt();
  print(int.tryParse(abc.toString().split('.')[1]));
//  int y = abc - x;
  final t = make<Test>(5);
  print(t);
}

abstract class Interface {
  Interface.func(int x);
}

class Test implements Interface {
  Test.func(int x) {}
}

/// Add factory functions for every Type and every constructor you want to make available to `make`
final factories = <Type, Function>{Test: (int x) => Test.func(x)};

T make<T extends Interface>(int x) {
  return factories[T](x);
}
like image 157
Günter Zöchbauer Avatar answered Sep 24 '22 16:09

Günter Zöchbauer