Search code examples
flutterdarttypesfuturestatic-analysis

Static type of Future<T> in classes not working | Dart


I want to make a Class in Dart with a static type of Future<T>. Because I want to implement its Call-Function async with type T, so I can call it like this:

MyFunction<T> func = MyFunction<T>();
T var = await func();

I tried to define this Class in that way:

class MyClass<Future<T>> {
  
 Future<T> call() async {
  //return a Future<T>
 }

}

It gives me a compiler error:

Expected to find '>'

It seems like it works only with type Future and not Future<foo>

Why does this not work? Is there another way to force the Type of the Class to be a Future of type T somehow?


Solution

  • Future cannot be part of your generic type. Instead just use T and return the Future parameterized with T in your function. Like this:

    void main() async {
      Test t = Test<String>();
      t.setVal("Hello World");
      String val = await t.getFuture();
      print(val);
    }
    
    class Test<T> {
      T? val;
      
      void setVal(T val) {
        this.val = val;
      }
      
      Future<T> getFuture() {
        return Future.value(val);
      }
    }