I was wondering how the following situation can be done?
I have the following code:
List<String> arrColorList = ['blue', 'red', 'yellow'];
return Scaffold(
backgroundColor: Colors.white,
body: Container(
child: Center(
child: Container(
child: Center(
child: SingleChildScrollView(
child: Container(
child: Padding(
padding: const EdgeInsets.all(36.0),
child: ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: arrColorList.length,
itemBuilder: (BuildContext context, int index) {
return new GestureDetector(
onTap: () {},
child: SizedBox(
width: 42.0,
height: 42.0,
child: const DecoratedBox(
decoration: const BoxDecoration(
color: const Color.fromRGBO(66, 165, 245, 1.0)
),
),
),
);
}),
),
),
),
),
),
),
)
);
}
What I want to achieve is to dynamically put the values of the arrColorList
to the color property like this:
Colors.arrColorList[index] // Should end up in Colors.blue or Colors.red
But that is not valid. Any idea how I could solve this?
CodePudding user response:
The getter 'arrColorList' isn't defined for the type 'Colors'.
Change color list type string to Color
List<Color> arrColorList = [Colors.blue, Colors.red, Colors.yellow];
Complete source code
Scaffold(
backgroundColor: Colors.white,
body: Container(
child: Center(
child: Container(
child: Center(
child: SingleChildScrollView(
child: Container(
child: Padding(
padding: const EdgeInsets.all(36.0),
child: ListView.builder(
scrollDirection: Axis.vertical,
shrinkWrap: true,
itemCount: arrColorList.length,
itemBuilder: (BuildContext context, int index) {
return new GestureDetector(
onTap: () {},
child: SizedBox(
width: 42.0,
height: 42.0,
child: DecoratedBox(
decoration: BoxDecoration(
color: arrColorList[index]),
),
),
);
}),
),
),
),
),
),
),
))
CodePudding user response:
It's good to create a List of Color "List" and fill it with what colors you want.
In your case you can do this:
List<Color> arrColorList = [
Colors.blue,
Colors.red,
Colors.yellow,
];
and then use it like this:
arrColorList[index]