如何使用for循环显示数组中的第一个元素

How to display the first element in array with for loop

我正在遍历一个数组,即 'companies' 使用 for 循环。我想使用 'for loop' 显示此数组中的第一个元素,而不必这样做 'companies[0].name'。这是我所做的工作,但我需要将它们用于循环。

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

您可以像下面的示例那样使用 ListBuilder,如果它的第一个元素 return 您的小部件,否则 return 空容器。

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

您可以使用集合包中的 mapIndexed or forEachIndexed 扩展方法。

import 'package:collection/collection.dart';

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

您可以使用内联函数来创建循环。不过,我建议在这里保持逻辑简单。大多数人更喜欢在您的案例中使用地图,正如@pskink 在评论部分所描述的那样。

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