简体   繁体   中英

Dart: using variables as method placeholders

Using this function:

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

On color: Colors.yourcolor . I keep getting the error:

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'.

I am aware that there isn't a method named 'yourcolor' but is there a way i can get the color i want using a function parameter?

You can't use String to pass the color. You have to pass the color itself.

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

and when you call the function pass the color as Colors.blue for example.

Thanks to jamesdlin i was able to create a map that points 'yourcolor' to it's corresponding color

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);
    },
  ),
);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM