Get subtype of Generic List in Dart

How can I get the subtype of a List which is a generic type in Dart?
For example:

T is List< String > => String

T is List< SomeObject > => SomeObject

I have researched for this questions but I just found some workarounds.
Any suggestions on this problem?

Upvotes: 1

Views: 6546

Answers (3)

TimMutlow
TimMutlow

Reputation: 305

To provide a more recent update for anyone still searching this:

From Dart 2.7 you can use an Extension Method to achieve this:

// extensions/list.dart

extension Typing<T> on List<T> {
    /// Provide access to the generic type at runtime.
    Type get genericType => T;
}

https://dart.dev/guides/language/extension-methods#implementing-generic-extensions

You then use it by importing it and using it like any other List function:

import './extensions/list.dart';

List<String> myList = ['some', 'strings'];

print('Your List type is ${myList.genericType}!');

This works with the caveat that it returns the declared type T so if this is a superclass of the type at runtime, you still only get whatever type the List was declared with in the first place.

Upvotes: 7

lrn
lrn

Reputation: 71693

There is no way to get the actual type argument of a list as a type at run-time. Dart has no way to deconstruct the type List<X> to get to X if the class itself does not provide one.

If dart:mirrors is available, you might be able to use it to find the type as a Type object, which should be sufficient for this case, but mirrors are not available in Flutter.

Upvotes: 6

Alexandre Ardhuin
Alexandre Ardhuin

Reputation: 76223

You can use the following function to get the type parameter of a List:

Type typeOfElementsInList<T>(List<T> e) => T;
main() {
  print(typeOfElementsInList([]));        // dynamic
  print(typeOfElementsInList(<int>[]));   // int
  print(typeOfElementsInList(['test']));  // String
}

Upvotes: 2

Related Questions