Dart:使用变量作为方法占位符



使用此函数:

buildButton(int file_number, String yourcolor, [String text]){
return Expanded(
child: FlatButton(
color: Colors.yourcolor,
child: Text(text),
onPressed: (){
playaudio(file_number);
},
),);
}

color: Colors.yourcolor。我一直收到错误:

The getter 'yourcolor' isn't defined for the class 'Colors'. Try importing the library that defines 'yourcolor', correcting the name to the name of an existing getter, or defining a getter or field named 'yourcolor'.

我知道没有一个名为"yourcolor"的方法,但有没有一种方法可以使用函数参数获得我想要的颜色?

您不能使用String来传递颜色。你必须传递颜色本身。

buildButton(int file_number, Color yourcolor, [String text]){
return Expanded(
child: FlatButton(
color: yourcolor,
child: Text(text),
onPressed: (){
playaudio(file_number);
},
),);
}

例如,当您调用函数时,将颜色传递为Colors.blue

多亏了jamesdlin,我能够创建一个将"你的颜色"指向其对应颜色的地图

buildButton(int file_number, String yourcolor){
Map match_colors = {'red':Colors.red, 'orange':Colors.orange, 'yellow':Colors.yellow,
'lightgreen': Colors.lightGreen, 'green':Colors.green, 'lightblue':Colors.lightBlue, 'purple':Colors.purple};
return Expanded(
child: FlatButton(
color: match_colors[yourcolor],
onPressed: (){
playaudio(file_number);
},
),
);
}

最新更新