Suppose list of colors are ,
List colors = [Colors.red, Colors.yellow,Colors.blue, Colors.green]; //4 colors and items are more than 4 , how do I repeat these colors for next items.
Expected result,
item1 - red, item2 - yellow, item3 - blue, item4 - green, item5 - red, item6 - yellow, item7 - blue, item8 - green,
Full Code
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
List colors = [Colors.red, Colors.yellow,Colors.blue, Colors.green];
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
body: Center(
child: MyWidget(),
),
),
);
}
}
class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return ListView.builder(
itemCount: 8,
itemBuilder: (BuildContext context,int index){
return ListTile(
tileColor: colors[index] ,
title:Text("List item $index")
);
}
);
}
}
CodePudding user response:
If you want a infinite list, set itemCount to null :)
CodePudding user response:
Add a variable that you can reference for the index from the color list.
int i = 0;
Then, on your ListView.builder builder function, check if you reached the end of the list.
ListView.builder(
itemCount: 8,
itemBuilder: (BuildContext context,int index){
if (i > colors.length) i = 0;
final color = colors[i];
i ;
return ListTile(
tileColor: color,
title:Text("List item $index")
);
}
)
I do not know if this is efficient but you get the idea.
CodePudding user response:
you can resize your color array:
colorsArray.removeRange(itemNameList.length, colorsArray.length);