Home > OS >  List != List<int> != List<String> != List<dynamic> How do i make sure if type == l
List != List<int> != List<String> != List<dynamic> How do i make sure if type == l

Time:09-20



listType(example) {
  var x = example.runtimeType;
  if (x == List) { 
    return true;
  } else {
    return false;
  }
}

print(listType([1, 2, 3, 4]));

You can swap swap x==List with x==List< int> and see the difference!!!

How do i make it so that runtimeType always returns true as long as the return type is a list?

CodePudding user response:

If you want to check the type use is and do not use runtimeType because it make x a type not list<int>, like this:

listType(example) {
  
  if (example is List) { //<--- here
    return true;
  } else {
    return false;
  }
}

CodePudding user response:

bool listType<T>(example){
  return example is List<T>;
}

example:

print(listType<int>([1,2,3])) //true
print(listType<dynamic>([1,2,3])) //true
print(listType([1,2,3])) //true
print(listType([1,2,"someString"])) //true
print(listType<int>([1,2,"someString"])) //false

CodePudding user response:

if you want to check specific type of list like list of int or list of string.

you can try it like this:

listType(example) {
    switch(example.runtimeType){
      case List<int>:
        print("int");
        break;
      case List<String>:
        print("String");
        break;
      case List<double>:
        print("double");
        break;
    }
  }
  • Related