Dart服务端从PostgreSQL bytea字段获取List<int>数据的问题
解决PostgreSQL bytea字段读取为List的问题
错误提示type 'ResultRow' is not a subtype of type 'List<int>' in type cast,本质是你没正确提取bytea字段的二进制数据,误把整个查询行(ResultRow类型)当成了字段值来转换。按以下步骤处理:
明确查询与结果提取逻辑
查询时要指定目标bytea字段,比如:final result = await connection.query('SELECT account_bytes FROM accounts WHERE id = @id', substitutionValues: {'id': 1});注意
result是查询结果集,result.first是单条结果的行对象(ResultRow),不能直接拿来转Protobuf。正确提取bytea字段的二进制数据
postgres插件会自动将bytea字段解析为Uint8List(属于List的子类),通过字段索引或字段名提取即可: // 方式1:通过字段索引提取(适合字段顺序固定的场景) final bytes = result.first[0] as Uint8List; // 方式2:通过字段名提取(更直观,不易出错) final bytes = result.first['account_bytes'] as Uint8List;拿到bytes后直接传给Protobuf的转换方法:
final account = Account.fromBuffer(bytes);处理多行查询结果
如果查询返回多条数据,遍历每行提取字段即可:for (final row in result) { final bytes = row['account_bytes'] as Uint8List; final account = Account.fromBuffer(bytes); // 处理每个Account对象 }验证字段类型(排查问题用)
不确定类型时,可以先打印字段的运行时类型确认:print(result.first['account_bytes'].runtimeType);如果输出不是Uint8List,检查数据库字段是否确实是bytea类型,同时确保postgres插件是最新版本。
内容的提问来源于stack exchange,提问作者user3262353
相关产品推荐
相关产品推荐

