How to display the first element in array with for loop

Issue

I am looping through an array i.e ‘companies’ using the for loop. I want to display the first element in this array using ‘for loop’ without having to do it this way ‘companies[0].name’. Here is what I have done which works but I need to use them for loop.

    child: Column(
      children: < Widget > [
        // for (var item in companies)
        companies.length > 0 ?
        Text(
          '${companies[0].name}'.toUpperCase(), // how can i replace this using the for loop
          style: TextStyle(
            color: AppColor.white,
          ),
        ) :
        Text('No Company Assigned '),
      ],
    ),

Solution

You can use the mapIndexed or forEachIndexed extension methods from the collection package.

import 'package:collection/collection.dart';

item.forEachIndexed((index, element) {
  print('index: $index, element: $element');
});

Answered By – Cenk YAGMUR

Answer Checked By – Mildred Charles (FlutterFixes Admin)

Leave a Reply

Your email address will not be published. Required fields are marked *