Flutter中如何访问Snapshot返回的自定义类对象内部的属性值?
解决方案
你可以直接通过点运算符访问Deposit类的公开属性,步骤如下:
- 确保你的
FutureBuilder已经指定泛型为Deposit,避免类型推断错误。 - 在确认
snapshot有数据之后,直接拿实例调用属性即可。
代码示例
FutureBuilder<Deposit>( // 此处替换为你返回Deposit实例的future方法 future: fetchDepositData(), builder: (context, snapshot) { // 加载状态处理 if (snapshot.connectionState == ConnectionState.waiting) { return const CircularProgressIndicator(); } // 错误状态处理 if (snapshot.hasError) { return Text('加载失败: ${snapshot.error}'); } // 拿到Deposit实例 Deposit deposit = snapshot.data!; // 访问属性示例 return Column( crossAxisAlignment: CrossAxisAlignment.start, children: [ Text('存款ID:${deposit.id}'), Text('交易金额:${deposit.amount}'), Text('支付状态:${deposit.ismarkedasPaid ? "已支付" : "未支付"}'), Text('创建时间:${deposit.createdAt}'), Text('当前状态:${deposit.status}'), // 其余属性都可以用 deposit.属性名 的格式直接访问 ], ); }, )
调试优化建议
如果你需要打印整个实例的所有属性排查问题,可以给Deposit类重写toString方法:
class Deposit { String id; String merchantId; String accountId; int amount; bool ismarkedasPaid; String paidAt; String completedAt; String status; String createdAt; String updatedAt; Deposit( {this.accountId, this.merchantId, this.amount, this.completedAt, this.createdAt, this.ismarkedasPaid, this.updatedAt, this.paidAt, this.status, this.id}); // 新增toString重写 @override String toString() { return 'Deposit{id: $id, merchantId: $merchantId, accountId: $accountId, amount: $amount, ismarkedasPaid: $ismarkedasPaid, paidAt: $paidAt, completedAt: $completedAt, status: $status, createdAt: $createdAt, updatedAt: $updatedAt}'; } factory Deposit.fromJson(Map<String, dynamic> json) { return Deposit( id: json['id'], merchantId: json['merchant_id'], accountId: json['account_id'], amount: json['amount'], ismarkedasPaid: json['is_marked_as_paid'], paidAt: json['paid_at'], completedAt: json['completed_at'], status: json['completed'], createdAt: json['created_at'], updatedAt: json['updated_at'], ); } }
之后直接调用print(deposit)就可以输出所有属性的具体值。
内容的提问来源于stack exchange,提问作者Godwin Alexander Ekainu
相关产品推荐
相关产品推荐

