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

Flutter中API列表展示异常:显示[Instance of 'Source']的解决问询

Flutter中展示List数据显示[Instance of 'Source']的解决方法

你遇到的问题是因为直接调用List<Source>的toString()方法时,Dart会默认输出每个元素的实例标识(比如Instance of 'Source'),而不是对象内部的具体数据。之前处理aspect.name能正常显示,是因为你直接访问了Aspect对象的具体属性,而非调用整个对象的toString()。

方案1:直接访问Source对象的具体属性(推荐)

直接从每个Source实例中提取需要展示的字段(比如text、type等),这是最灵活的实现方式:

ListView.builder(
  shrinkWrap: true,
  itemCount: finalApi![widget.index].sources.length,
  itemBuilder: (context, index) {
    // 获取当前索引对应的Source对象
    final Source currentSource = finalApi![widget.index].sources[index];
    // 组合type和text字段展示,可根据需求调整格式
    String displayText = '${typeValues.reverse[currentSource.type]}: ${currentSource.text}';
    return Text(displayText);
  },
),

方案2:给Source类重写toString()方法

如果希望直接调用source.toString()就能得到可读内容,可以在Source类中重写toString()方法,自定义输出格式:

class Source {
  Source({
    required this.type,
    required this.text,
    required this.relatedType,
    required this.relatedId,
  });

  Type? type;
  String text;
  dynamic relatedType;
  dynamic relatedId;

  // 保留原有的fromMap和toMap方法不变

  // 重写toString方法,自定义输出内容
  @override
  String toString() {
    return '${typeValues.reverse[type]}: $text';
  }
}

之后ListView代码可简化为:

ListView.builder(
  shrinkWrap: true,
  itemCount: finalApi![widget.index].sources.length,
  itemBuilder: (context, index) {
    return Text(finalApi![widget.index].sources[index].toString());
  },
),

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.12 15:15:36