Search code examples
flutterlistdartsublist

checking wether the range of sublist is valid


Hi I have a simple list like this:

List x=["a","b","c","d","e"];

and I would like to check when I print x.sublist(1,10) => it will get "invalid" string result and when I print x.sublist(1,2) =>it will get "valid" string result. Is there a way to do that ?


Solution

  • You could write a function to test that:

    bool isValidSublist(List x, int start, int end) {
      return !(start < 0 ||
          start > x.length ||
          end < 0 ||
          end < start ||
          end > x.length);
    }
    
    List x = ["a", "b", "c", "d", "e"];
    print(isValidSublist(x, 1, 10) ? 'valid' : 'invalid');
    print(isValidSublist(x, 1, 5) ? 'valid' : 'invalid');
    

    Hope this helps.