Home > OS >  Why can't I add items from one list to another in flutter?
Why can't I add items from one list to another in flutter?

Time:09-15

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,

  1. y = 0 for the indexed for loop

  2. 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]);
        }
       }
    
  • Related