Home > Enterprise >  How to display the first element in array with for loop
How to display the first element in array with for loop

Time:11-25

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

CodePudding user response:

You can use an inline function to create a loop. Though, I will suggest keep the logic simple here. And most prefer using map in your case as @pskink describe on comment section.

 Column(
        children: [
          () {
            // do the thing you want and return
            return companies.isEmpty
                ? Text('No Company Assigned ')
                : Text(companies.first.toUpperCase());
          }(),
        ],
      ),

CodePudding user response:

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');
});

CodePudding user response:

You can use ListBuilder like below example, if its first element return your widget, else return empty container.

final List<String> entries = <String>['A', 'B', 'C'];
final List<int> colorCodes = <int>[600, 500, 100];

ListView.builder(
  padding: const EdgeInsets.all(8),
  itemCount: entries.length,
  itemBuilder: (BuildContext context, int index) {
    return index == 0  ? Container(
      height: 50,
      color: Colors.amber[colorCodes[index]],
      child: Center(child: Text('Entry ${entries[index]}')),
    ): Container();
  }
);
  • Related