Gerneric Methods

Initially, Dart’s generic support was limited to classes. A newer syntax, called generic methods, allows type arguments on methods and functions:

Example :


T lastElementOfList<T>(List<T> lt) {

  T last = lt[lt.length - 1];

  return last;

}

 

void main() {

  lastElementOfList([1467]); // 7

  lastElementOfList(["dart""flutter""apps"]); // apps

  lastElementOfList([falsetruefalsetrue]); // true

}



Here the generic type parameter on lastElementOfList <T> allows you to use the type argument T in several places:

  • In the function’s return type T

  • In the type of an argument List<T>

  • In the type of a local variable T lt