The operator '[]=' isn't defined for the type 'String'

Viewed 158

I'm getting an error in this code:

void main() {
  List<String> wave(String str) {
    List<String> results = [];
    String newStr;
    int i = 0;
    for (String ltr in str.split('')) {
      newStr = str;
      if (ltr != ' ') {
        newStr[i] = ltr.toUpperCase();
        results.add(newStr);
      }
      i++;
    }
    return results;
  }

  print(wave('   gap   '));
}

the error is at the line:

newStr[i] = ltr.toUpperCase;

Despite when I try print(newStr[i]); I don't get an error and the code is executed correctly!

2 Answers

In Dart String operation, operator[] returns a string. Which means, array[index] is used for getting the string in the index position. That is why you're getting that error, because you can't set at specific index using this operator[] in dart. See the documentation for details.

To replace at the specific index in dart, you can use replaceFirst(Pattern from, String to, [int startIndex = 0]) as the other answer mentioned. Or, you can use substring(int start, [int? end]) as follows:

  if (ltr != ' ' && i < newStr.length) {
    newStr = newStr.substring(0, i) + ltr.toUpperCase() + newStr.substring(i+1);
    results.add(newStr);
  }

To make the code bug free, I've added the checking of the value of i in it. You should add the checking to avoid out of bound access.

try to replace

newStr[i] = ltr.toUpperCase();

to

newStr = newStr.replaceFirst(ltr,ltr.toUpperCase(),i);

So the result will be [ Gap , gAp , gaP ]

Honestly, I don't know how char is defined in Dart, but I think accessing index of String is kind of getter, thus cannot be set to a new value.

Related