Home > Blockchain >  Is it possible to create a List in Dart/Flutter using a variable as the type?
Is it possible to create a List in Dart/Flutter using a variable as the type?

Time:10-19

Is it possible to assign a type to a variable and then use that to create a type-based object, such as a List? My use case is that I have a Flutter widget using a particular data type to create a List for a FutureBuilder. If I could parameterise the type rather than hard-coding it then I could re-use the widget for multiple data types.

I have tried to do this in DartPad as follows:

void main() {
  A a = A(int);
  a.stuff();
}

class A {
  A(Type type) {
    _type = type;
  }
  late Type _type;

  void stuff() {
    print('$_type');     // prints out 'int'
    List<_type> b = [];
  }
}

If I comment out the line List<_type> b = []; then the code works and the output is int.

However, if I include the List<> line then I get the error "The name '_type' isn't a type so it can't be used as a type argument."

If have found next to nothing on the internet about this so think it might not be possible.

I have also had a look at the question on stack overflow here, which seems to be a similar question. This uses generics, which I know nothing about, and I couldn't make it work in my case. Is this a similar problem to mine and is it worth me doing some more exploration down this path?

My other idea was to pass a specific instance of the type that I want and then use runtimeType to get the type. I have tried this in Dart and it also gives an error.

void main() {
  A a = A(1);
  a.stuff();
}

class A {
  A(this.value){}
  dynamic value;

  void stuff() {
    print('${value.runtimeType}');     // prints out 'int'
    List<value.runtimeType> b = [];
  }
}

If I comment out the List<> line then the code outputs int.

However, with the list line uncommented, it gives the error "'type.runtimeType' can't be used as a type because 'type' doesn't refer to an import prefix."

Does anyone know if it possible to do what I want? Thanks.

CodePudding user response:

Dart supports generic types. SO you can do something like

class A<T> {

  void stuff() {
    List<T> b = [];
  }
}

And use it as

A<int>, A<String>

whatever type you need

CodePudding user response:

you can use generics as this example :

class A<T> {
  List<T> stuff() {
    List<T> b = [];
    return b;
  }
}

then when you want to call this :

A a = A<int>();
List c = a.stuff();

this is a simple demo to understand the generic.

  • Related