【问题标题】:How to display the first element in array with for loop如何使用for循环显示数组中的第一个元素
【发布时间】:2022-01-02 21:59:20
【问题描述】:

我正在使用 for 循环遍历一个数组,即“公司”。我想使用'for循环'显示这个数组中的第一个元素,而不必这样做'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 '),
      ],
    ),

【问题讨论】:

  • companies.length &gt; 0 ? ...companies.map((c) =&gt; Text('${c.name}')) : Text('No Company Assigned ')
  • 你为什么不想使用companies[0].name,为什么需要使用for loop,你能澄清你的问题吗?
  • @YeasinSheikh 因为我以后仍然需要 for 循环和一个因为我想知道是否有使用 for 循环的解决方法。
  • @pskink 您的建议会显示数组中的所有元素。如何修改它以仅显示第一个元素?
  • 等等,如果你想要第一个元素,你需要一个循环来做什么?如果它只有一个孩子,你需要Column 做什么?你到底想达到什么目标?

标签: flutter for-loop dart flutter-web


【解决方案1】:

您可以使用内联函数来创建循环。不过,我建议在这里保持逻辑简单。并且大多数人更喜欢在您的情况下使用地图作为@pskink 在评论部分的描述。

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

【讨论】:

    【解决方案2】:

    您可以使用集合包中的mapIndexedforEachIndexed 扩展方法。

    import 'package:collection/collection.dart';
    
    item.forEachIndexed((index, element) {
      print('index: $index, element: $element');
    });
    

    【讨论】:

      【解决方案3】:

      你可以像下面的例子一样使用 ListBuilder,如果它的第一个元素返回你的小部件,否则返回空容器。

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2022-07-21
        • 1970-01-01
        相关资源
        最近更新 更多