For simple data types, you can use e.g.
object is String
to check whether an Object variable is of a more specific type.
But let's you have a List, but want to check if it is a List of Strings. Intuitively we might try
List list = ['string', 'other string'];
print(list is List<String>);
which returns false.
Similarly using the List.cast() method doesn't help, it will always succeed and only throw an error later on when using the list.
We could iterate over the entire list and check the type of each individual entry, but I was hoping there might be a better way.
CodePudding user response:
There is no other way. What you have is a List<Object?>
/List<dynamic>
(because the type is inferred from the variable type, which is a raw List
type which gets instantiated to its bound). The list currently only contains String
objects, but nothing prevents you from adding a new Object()
to it.
So, the object itself doesn't know that it only contains strings, you have to look at each element to check that.
Or, when you create a list, just declare the variable as List<String> list = ...;
or var list = ...;
, then the object will be a List<String>
.
If you are not the one creating the list, it's back to list.every((e) => e is String)
.