FeelRightz
FeelRightz

Reputation: 2999

dart import to define <T>

I wish to check any list pass into checkList function. What import I should use for <T>. VS Code no suggest a Quick Fix for this.

enter image description here

The name 'T' isn't a type so it can't be used as a type argument.
Try correcting the name to an existing type, or defining a type named 'T'.

Upvotes: 0

Views: 703

Answers (3)

cameron1024
cameron1024

Reputation: 10156

If you want to be able to check any list with any contents, you should use:

void checkListObject(List<Object> list) {
  // ...
}

If you want to enforce that the list has a concrete type, but you don't know what that is ahead of time, you can pass a type parameter to the function:

void checkListT<T>(List<T> list) {
  // ...
}

This has the following behaviour:

checkListObject(["hello", 123]);  // allowed
checkListObject([123, 234]);  // allowed

checkListT(["hello", 123]);  // allowed, T is Object
checkListT<String>(["hello", "world"]);  // allowed, T is String
checkListT<String>([123, 234]);  // not allowed, T is String but given List<int>
checkListT<String>([123, "hello"]);  // not allowed, T is String but given List<Object>

Upvotes: 1

Kohls
Kohls

Reputation: 908

If you want to type safe you should do this

void checkList<T>(List<T> list){
   // ... 
}

Upvotes: 1

Ruben R&#246;hner
Ruben R&#246;hner

Reputation: 601

You can use Object instead of T.

void checkList(List<Object> list){
     
}

Upvotes: 0

Related Questions