Like Java, Dart also supports generic methods. Since a generic method performs intended actions on multiple kinds of data types, it removes the need to have various overloaded methods and promotes code reusability.
Dart supports the use of generic types (often denoted as T
) in three general places:
Let’s look at an example where we want a generic function to return the item at the first index of a list of generic type T
. The code below uses T
in all three places we discussed above:
import 'dart:convert';//This generic function prints and returns the item at the first index (0) of a listT printFirst<T>(List<T> lst) { //List of generic type taken as function argumentT first = lst[0]; //Generic type as local variableprint(first);return first; //Generic type as return value}void main() {//Lists of three different data types declaredList<int> intList = [2, 4, 9, 10];List<double> doubleList = [5.2, 9.1, 1.2, 3.5];List<String> stringList = ["cat", "giraffe", "panther", "scorpion"];//Generic function printFirst called on Lists if different timesprintFirst(intList);printFirst(doubleList);printFirst(stringList);}
Free Resources