I thinking about how I can add list to function then add by ListView.builder , I trying 7 often but app give me error enter image description here I'm dont know how but I search for this topic I'm read document enter link description here I'm try this way in this document and try change some line in this document
import 'package:flutter/material.dart';
class ColorsPage2 extends StatefulWidget {
const ColorsPage2({Key? key}) : super(key: key);
@override
State<ColorsPage2> createState() => _ColorsPage2State();
}
class _ColorsPage2State extends State<ColorsPage2> {
final List<String> entries = <String>[
'Red',
'Pink',
'Purple',
'DeepPurple',
'Indigo',
'Blue',
'LightBlue',
'Cyan',
'Teal',
'Green',
'LightGreen',
'Lime',
'Yellow',
'Amber',
'Orange',
'DeepOrange',
'Brown',
'Grey',
'BlueGrey',
];
List<MaterialColor> colorCodes = <MaterialColor>[
Colors.red,
Colors.pink,
Colors.purple,
Colors.deepPurple,
Colors.indigo,
Colors.blue,
Colors.lightBlue,
Colors.cyan,
Colors.teal,
Colors.green,
Colors.lightGreen,
Colors.lime,
Colors.yellow,
Colors.orange,
Colors.deepOrange,
Colors.brown,
Colors.grey,
Colors.blueGrey,
];
Widget cardColor({MaterialColor? color, String? title, String? hexColor}) {
return InkWell(
child: Card(
color: colorCodes[colorCodes.length],
child: ListTile(
textColor: Colors.white,
title: Text(entries[entries.length]),
subtitle: SelectableText(
'This Is ${entries.length} Color , Hex: #$hexColor'),
),
),
);
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
padding: const EdgeInsets.all(8),
itemCount: entries.length,
itemBuilder: (BuildContext context, int index) {
return cardColor(
color: colorCodes[colorCodes.length],
title: entries[entries.length],
hexColor: 'F44336FF',
);
},
),
);
}
}
CodePudding user response:
You should use the index, you are using the length instead;
try this:
Widget build(BuildContext context) {
return Scaffold(
body: ListView.builder(
padding: const EdgeInsets.all(8),
itemCount: entries.length,
itemBuilder: (BuildContext context, int index) {
return cardColor(
color: colorCodes[index],
title: entries[index],
hexColor: 'F44336FF',
);
},
),
);
}
CodePudding user response:
color: colorCodes[colorCodes.length],
title: entries[entries.length],
The length property give you the size of a list starting from 1. You try to access colorCodes[colorCodes.length] and will not work because a list start from 0 so you need to do colorCodes[colorCodes.length - 1] for example.