【问题标题】:How to get index number forEach iterable value in Dart (Flutter)如何在 Dart (Flutter) 中获取每个可迭代值的索引号
【发布时间】:2020-10-13 02:27:25
【问题描述】:

我需要 index 数字 forEach 可迭代值,因为我想更新我的数据表。但是为了更新数据表,我需要列 ID。这就是为什么我想要每个值的索引号并将其分配给 > i。 有类似的问题解释了如何获取可迭代的索引。但就我而言,我未能映射 CallLogEntry,这就是为什么我无法获取此可迭代值的索引。

Future callLogDB() async {
    Iterable<CallLogEntry> cLog = await CallLog.get();
    final dbHelper = DatabaseHelper.instance;
    int i = 0;
    cLog.forEach((log) async {
      i++;
      // row to insert
      Map<String, dynamic> row = {
        //DatabaseHelper.columnId: 2,
        DatabaseHelper.columnName: '${log.name}',
        DatabaseHelper.columnNumber: '${log.number}',
        DatabaseHelper.columnType: '${log.callType}',
        DatabaseHelper.columnDate:
            '${DateTime.fromMillisecondsSinceEpoch(log.timestamp)}',
        DatabaseHelper.columnDuration: '${log.duration}'
      };
      await dbHelper.insert(row);
      print('CallLog $i:: $row');
    });
    return cLog;
  }

【问题讨论】:

  • 我无法理解这个问题。我需要针对我的问题的解决方案。
  • 我无法映射 CallLogEntry。这就是为什么我无法获得可迭代值的索引。
  • 如果转换为基于索引的for 循环会发生什么?我在下面的答案中添加了转换后的代码。
  • 我尝试了 for 循环。但不幸的是,我的应用程序崩溃了。
  • 它给出的错误是什么?

标签: database flutter dart foreach iterable


【解决方案1】:

我无法映射 CallLogEntry。

首先,您需要使用toList() 方法将Iterable&lt;CallLogEntry&gt; 转换为列表,然后您可以使用asMap()

示例代码

 Iterable<CallLogEntry> cLog = await CallLog.get();
 cLog.toList().asMap().forEach((cLogIndex, callLogEntry) {

      row.forEach((index, data) {

      });

    });

编辑

Future callLogDB() async {
  Iterable<CallLogEntry> cLog = await CallLog.get();
  final dbHelper = DatabaseHelper.instance;
  int i = 0;
  cLog.toList().asMap().forEach((cLogIndex, callLogEntry) {

    Map<String, dynamic> row = {
      //DatabaseHelper.columnId: cLogIndex,
      DatabaseHelper.columnName: '${cLogIndex.name}',
      DatabaseHelper.columnNumber: '${cLogIndex.number}',
      DatabaseHelper.columnType: '${cLogIndex.callType}',
      DatabaseHelper.columnDate:
      '${DateTime.fromMillisecondsSinceEpoch(cLogIndex.timestamp)}',
      DatabaseHelper.columnDuration: '${cLogIndex.duration}'
    };
    await dbHelper.insert(row);

  });
  return cLog;
}

【讨论】:

  • 您以前以非常简单的方式帮助了我。我试过你对这篇文章的解决方案。但我失败了。也许我无法正确实施您的解决方案。请用您的解决方案编辑我的代码。请。
  • 你太棒了!!!它进行了轻微的修改。 cLogIndex.nember 给出错误,因为 cLogIndex 是索引号。我试过 callLogEntry.number。它有效!非常感谢。
猜你喜欢
  • 1970-01-01
  • 2013-07-05
  • 2019-07-05
  • 1970-01-01
  • 2020-07-20
  • 2013-01-03
  • 2022-01-04
  • 2021-09-03
  • 2014-10-28
相关资源
最近更新 更多