如何将列表更改为小写? for循环中不断出错

How to change a list to lower case? Keep getting error in for loop

这是我用于锻炼的代码。我想将输入的颜色更改为小写,以确保不会出现任何错误。但是我现在的方式在 for 循环 "the typed string used in the for loop must implement iterable dart" 上给我一个错误。有帮助吗?

void main(){
  ResistorColorDuo obj = new ResistorColorDuo();
  obj.result(['Orange','Black']); //I want something that would make these colours lower case so there's no error if someone types it with upper case
}

class ResistorColorDuo {
  static const COLOR_CODES = [
    'black', 'brown', 'red', 'orange', 'yellow', 'green', 'blue', 'violet', 'grey', 'white',];

  void result(List<String> givenColors) {
    String numbers = '';
    for (var color in givenColors.toString().toLowerCase()) {//But this throws an error "the type string used in the for loop must implement iterable dart"
      numbers = numbers + COLOR_CODES.indexOf(color).toString();
    }
    if (givenColors.length != 2)
      print ('ERROR: You should provide exactly 2 colors');

    else
      print (int.parse(numbers));
  }
}

答案在这里。 你的错误在这里 givenColors.toString().toLowerCase() givenColors() 是一个列表,并且列表不能转换为字符串,因为你在 for 循环中给出。在下面的代码中,我们从列表中取出一个值,然后转换为小写。

此行 color.toLowerCase() 将值转换为小写,因为 color 每次迭代都包含列表中的单个值。

Updated Code

void main(){
  ResistorColorDuo obj = new ResistorColorDuo();
  obj.result(['Orange','Black']); //I want something that would make these colours lower case so there's no error if someone types it with upper case
}

class ResistorColorDuo {
  static const COLOR_CODES = [
    'black', 'brown', 'red', 'orange', 'yellow', 'green', 'blue', 'violet', 'grey', 'white',];

  void result(List<String> givenColors) {
    String numbers = '';
    for (var color in givenColors) {//But this throws an error "the type string used in the for loop must implement iterable dart"
      numbers = numbers + COLOR_CODES.indexOf(color.toLowerCase()).toString();
    }
    if (givenColors.length != 2)
      print ('ERROR: You should provide exactly 2 colors');

    else
      print (int.parse(numbers));
  }
}

givenColors.toString() 将您的列表转换为 String;所以不能迭代;

您可以采取的解决方案很少;

List colorsLowercase = [];
for (var color in givenColors) {
  colorsLowercase.add(color.toLowerCase())
  ...
}

或者像@pskink 推荐的那样

givenColors.map((c) => c.toLowerCase())