by @kodeazy

Error RangeError (index) Index out of range index should be less than 4 4

Home » flutter » Error RangeError (index) Index out of range index should be less than 4 4
import 'package:flutter/material.dart';
void main() {
  String stringToReverse = "accaqqq";
  String reversedString = "";
   for (int j = stringToReverse.length; j >= 0; j--) {//stringToReverse.length gives 7 as j value but total length of stringToReverse variable is 6 so we got RangeError
    reversedString += stringToReverse[j];                
  }
  print(reversedString);
}
  • In the above code stringToreverse variable length is 6.
  • stringToReverse.length gives length as 7.
  • As the stringToReverse.length length is greater than the string lenght we got below error. Output:

    Error: RangeError (index): Index out of range: index should be less than 7: 7
    at Object.throw_ [as throw] (http://localhost:61643/dart_sdk.js:5041:11)
    at String.[dartx._get] ....
  • By modifying stringToReverse.length to stringToReverse.length-1 we make sure that getting index with in the string range.

    import 'package:flutter/material.dart';
    void main() {
    String stringToReverse = "accaqqq";
    String reversedString = "";
    for (int j = stringToReverse.length-1; j >= 0; j--) {
    reversedString += stringToReverse[j];
    }
    print(reversedString);
    }

    Output:

    qqqacca