如何在 Dart (Flutter) 中获取每个可迭代值的索引号

San*_*kil 3 database foreach iterable dart flutter

我需要的索引的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;
  }
Run Code Online (Sandbox Code Playgroud)

Nil*_*hod 5

我无法映射 CallLogEntry。

首先,您需要Iterable<CallLogEntry>使用toList()方法转换为列表,然后您可以使用asMap()

示例代码

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

      row.forEach((index, data) {

      });

    });
Run Code Online (Sandbox Code Playgroud)

编辑

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;
}
Run Code Online (Sandbox Code Playgroud)