0

Simplified Question:

Starting with dynamic x = [a, b] where a and b are String.

The following cast fails, i.e. the print out is 'fail':

if(x is List<String>){
  print('pass');
} else{
  print('fail');
}

I think the above is the simplified version of my question, but in case you need more info, see below for more detailed version.

More Detailed Question (if needed)

I have a dynamic List that can be any number of levels deep. For example, it may start like this:

x = [a, [b, c, d], [e, [f, g, h], i]]

Where each letter above is a String. I'm looping through to unwrap it and can catch it when it gets to the final String by doing:

if(x is String) { ... } // Works!

But, when I try to catch it one level before becoming a String, List<String> it will never match. For example, the following doesn't work EVEN when the dynamic it is given is a List<String>:

if(x is List<String>) {...} // Doesn't work

Why isn't List<String> ever true?

More complete example:

x = [a, [b, c, d], [e, [f, g, h], i]]
for (var i = 0; i < x.length; i++) {
    if(x is List<String>){ ... } // Never works even if print(x) prints [b, c, d]
    else if(x is String){ ... } //Works!
    else { ... } // Works obviously
}
Coltuxumab
  • 615
  • 5
  • 16

1 Answers1

1

As you might declare b, c, and d as dynamic, Flutter considers as List<dynamic>, so you have to give typed List as following..

x = [a, <String>[b, c, d], [e, <String>[f, g, h], i]]

Or

You have to check with dynamic List

if (x is List) { ... }
Alex Sunder Singh
  • 2,378
  • 1
  • 7
  • 17
  • So the dynamic lists (i.e. x) is already determined and there are tons of them, all slightly different. So I can't declare the as far as I can tell. That's why I'm trying to detect it instead. Your second option works to identify the List, but then List can be `List` (i.e. `List>` or `List` or something else), so I'm trying to capture the instance where it's `List` only. Maybe I can do `if(x is List && SOMETHING ELSE)`? – Coltuxumab Mar 04 '23 at 15:53
  • 2
    @Coltuxumab You can test every element with `x.every((e) => e is String)`. – jamesdlin Mar 04 '23 at 16:40