I have a list with data and I want to add elements with an even index multiple of 2 to another list and display it. I do all this through a for loop, but I ran into an error The method '<=' was called on null. How can I solve this error?
class _ListPoyntsBookingsState extends State<ListPoyntsBookings> {
final List<String> orders = const [
'Sun',
'Mon',
'Mon',
'Sunday',
'Sun',
'Mon',
'Mon',
'Sunday',
];
List<String> pendingOrders = [];
@override
Widget build(BuildContext context) {
for (var y; y <= orders.length; y ) {
if (y % 2 == 0) {
pendingOrders.add(orders[y]);
}
}
CodePudding user response:
It has to be,
y = 0 for the indexed for loop
y < orders.length not y <= orders.length (or else it will give you indexOut-of-bound exception since you start from 0 )
for (var y = 0; y < orders.length; y ) { if (y % 2 == 0) { pendingOrders.add(orders[y]); } }