Home > Net >  Is it possible to assign a string as a parameter in flutter?
Is it possible to assign a string as a parameter in flutter?

Time:09-09

I am trying to go though this list of strings and get a box colored at each color, is it possible in any other way I am missing?

List<String> myColors = [
  "blue",
  "red",
  "green",
  "orange",
  "purple",
  "yellow",
  "pink",
  "black"
];
----------------------------------
ListView.builder(
              shrinkWrap: true,
              padding: const EdgeInsets.only(left: 5, right: 5),
              itemCount: myColors.length,
              itemBuilder: (BuildContext context, int index) {
                final currentColor = [myColors[index]];
                final coloring = "Colors.$currentColor";
                return Container(
                  height:30,
                  width: 160,
                  color: coloring,
                  child: Text(coloring),
                );
              },
            ),

CodePudding user response:

Try the following code:

List<Color> myColors = [
  Colors.blue,
  Colors.red,
  Colors.green,
  Colors.orange,
  Colors.purple,
  Colors.yellow,
  Colors.pink,
  Colors.black,
];

ListView.builder(
  shrinkWrap: true,
  padding: const EdgeInsets.only(left: 5, right: 5),
  itemCount: myColors.length,
  itemBuilder: (BuildContext context, int index) {
    final currentColor = myColors[index];
    return Container(
      height: 30,
      width: 160,
      color: currentColor,
      child: Text(currentColor.toString()),
    );
  },
),

CodePudding user response:

With the current API it is not possible to get the right 'Color' instance by just providing the name of the color. Your options are:

  1. Have a look at libraries like color
  2. Provide a list of hex, argb or rgbo values or Color instances instead of names
  3. Try to get a premade map which maps all color names to the corresponding values
  • Related