How to display the first element in array with for loop

Question

Asked by Emmon on November 24, 2021 (source).

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 '),
      ],
    ),

Answer

Question answered by Cenk Y (source).

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');
});
DART FLUTTER FLUTTER-WEB FOR-LOOP
SHARE: