You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何借助数据模型的fromMap从数据库返回单条VoterRecord记录?

问题:无法将SQLite查询结果转为VoterRecord类型

尝试使用带fromMap方法的数据模型从SQLite数据库获取单条记录,确认能成功获取数据,但无法将结果转换为VoterRecord类型,具体细节如下:

报错的获取单条记录代码

final data = await SQLiteMethods.getSingleVoter(voterId);

static Future<VoterRecord> getSingleVoter(int voterId) async {
  final db = await SQLiteMethods.db();
  final tempList = db.query('Voters',
      where: "VoterId = ?", whereArgs: [voterId], limit: 1);
  return VoterRecord.fromMap(tempList[0]);    // [0]处报错
}

错误信息

The operator '[]' isn't defined for the type 'Future<List<Map<String, Object?>>>'. (Documentation) Try defining the operator '[]'.

VoterRecord模型代码

class VoterRecord {

  static const String voterIdTag = "VoterId";
  static const String firstNameTag = "FirstName";
  static const String middleNameTag = "MiddleName";
  static const String lastNameTag = "LastName";

  int? voterId;
  String? firstName;
  String? middleName;
  String? lastName;

  VoterRecord({
    this.voterId,
    this.firstName,
    this.middleName,
    this.lastName,
  });

  Map<String, dynamic> toMap() {
    var map = <String, dynamic>{
      firstNameTag: firstName,
      middleNameTag: middleName,
      lastNameTag: lastName,
    };
    if (voterId != null) {
      map[voterIdTag] = voterId;
    }
    return map;
  }

  VoterRecord.fromMap(Map<String, dynamic> map) {
    voterId = map[voterIdTag];
    firstName = map[firstNameTag];
    middleName = map[middleNameTag];
    lastName = map[lastNameTag];
  }
}

可运行但不符合需求的代码

已确认能获取数据,但以下代码返回的是List<Map<String, dynamic>>类型,而非需要的VoterRecord:

static Future<List<Map<String, dynamic>>> getVoter(int voterId) async {
  final db = await SQLiteMethods.db();
  return db.query('Voters',
      where: "VoterId = ?", whereArgs: [voterId], limit: 1);
}

解决方案

问题核心是db.query是异步方法,返回的是Future<List<Map<String, Object?>>>,原代码未加await,导致tempList是Future对象而非实际的列表,因此无法使用[]索引。

修改后的getSingleVoter方法:

static Future<VoterRecord> getSingleVoter(int voterId) async {
  final db = await SQLiteMethods.db();
  // 加上await获取实际查询结果
  final tempList = await db.query('Voters',
      where: "VoterId = ?", whereArgs: [voterId], limit: 1);
  
  // 处理未找到记录的情况,避免索引越界
  if (tempList.isEmpty) {
    throw Exception("未找到ID为$voterId的选民记录");
    // 若允许返回null,可改为return null,同时方法返回类型改为Future<VoterRecord?>
  }
  
  return VoterRecord.fromMap(tempList[0]);
}

关键说明

  1. 给db.query添加await,等待异步操作完成后获取真实的列表数据。
  2. 增加空列表判断,防止查询不到记录时访问tempList[0]引发异常,可根据业务需求选择抛异常或返回null。

内容的提问来源于stack exchange,提问作者SqueezeOJ

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.30 19:45:31