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

u5rb5r59  于 2023-05-19  发布在  Flutter
关注(0)|答案(1)|浏览(138)

我需要indexnumberforEach可迭代值,因为我想更新我的数据表。但是为了更新数据表,我需要列ID。这就是为什么我需要每个值的索引号并将其分配给> i。对于如何求可迭代的索引也有类似的问题。但在我的例子中,我MapCallLogEntry失败,这就是为什么我无法获得此可迭代值的索引。

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;
  }
ar5n3qh5

ar5n3qh51#

我无法MapCallLogEntry。
首先,您需要使用toList()方法将Iterable<CallLogEntry>转换为列表,然后可以使用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;
}

相关问题