Reputation: 441
I'd like to generate a horizontal scrollable list using a different color for each list item.
Without the 'loop' provided by ListView.builder, I can define a color swatch using Colors.red
, to get the color red, for instance.
The 'property' indicator of the Colors object does not work using the method I tried below, using the swatch names in the type of String.
What is the right type to use?
import 'package:flutter/material.dart';
class SubscriptionFilter extends StatelessWidget {
final List<String> colors = <String>['red', 'blue', 'green', 'yellow', 'orange'];
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.symmetric(vertical: 20.0),
height: 75.0,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: colors.length,
itemBuilder: (BuildContext context, int index) {
return Container(
width: 100.0,
color: Colors[index],
);
}
),
);
}
}
Upvotes: 0
Views: 8313
Reputation: 5753
Following is the working code for your reference:
import 'package:flutter/material.dart';
class SubscriptionFilter extends StatelessWidget {
final List<Color> colors = <Color>[Colors.red, Colors.blue, Colors.green, Colors.yellow, Colors.orange];
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.symmetric(vertical: 20.0),
height: 75.0,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: colors.length,
itemBuilder: (BuildContext context, int index) {
return Container(
width: 100.0,
color: colors[index],
);
}
),
);
}
}
Upvotes: 0
Reputation: 7990
Passing colors as 'red' or 'blue' will not work, you need to modify code like below.
class SubscriptionFilter extends StatelessWidget {
final List<Color> colors = <Color>[Colors.red, Colors.blue,Colors.amber];
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.symmetric(vertical: 20.0),
height: 75.0,
child: ListView.builder(
scrollDirection: Axis.horizontal,
itemCount: colors.length,
itemBuilder: (BuildContext context, int index) {
return Container(
width: 100.0,
color: colors[index],
);
}
),
);
}
}
Upvotes: 3