Get the depth of a List in flutter/dart

65 views Asked by At

How do you get the depth of a List in flutter/ dart language, given a list like this one

List testRy = [1,2,[3,4,[5,6],7,[8,[9,91]],10],11,12];

Can you help me create something like an extension for doing that, that is callable from anywhere?

1

There are 1 answers

0
Frankline Sable On

I found a solution!

Created a list extension as below:

extension Lists<E> on List<E> {
  int get depth {
    int depth = 0;
    getElementDepth(List list) {
      depth++;
      for (var item in list) {
        if (item is List) {
          getElementDepth(item);
        }
      }
      return depth;
    }

    return getElementDepth(this);
  }
}

and now I can call use it like this:

let test = [1,2,[3,4,[5,6],7,[8,[9,91]],10],11,12];

print(test.depth);