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

Flutter中FutureBuilder显示Test实例而非JSON数据的问题排查

问题解决:Flutter FutureBuilder显示JSON格式数据而非Instance of 'Test'

问题原因

你当前直接调用snapshot.data.toString(),而snapshot.data是List<Test>类型。List的默认toString()会逐个调用元素的默认toString()方法,你的Test类未重写该方法,因此每个元素都会输出Instance of 'Test',最终呈现为[Instance of 'Test', Instance of 'Test']。

解决方案

要生成预期的标准JSON格式字符串,需要两步操作:

  1. 遍历List<Test>,调用每个Test对象的toJson()方法,将实例转为Map<String, dynamic>
  2. 使用dart:convert包的jsonEncode方法,将整个Map列表编码为JSON字符串

修改后的代码

首先导入dart:convert包:

import 'dart:convert';

然后更新FutureBuilder的builder逻辑:

FutureBuilder(
  future: getTest.getTest(),
  builder: (context, snapshot) {
    // 处理加载中状态
    if (snapshot.connectionState == ConnectionState.waiting) {
      return const CircularProgressIndicator();
    }

    // 处理错误状态
    if (snapshot.hasError) {
      return Text('加载失败: ${snapshot.error}');
    }

    // 处理数据展示
    if (snapshot.hasData && snapshot.data != null) {
      final List<Test> testList = snapshot.data!;
      // 转换为标准JSON字符串
      final jsonOutput = jsonEncode(testList.map((test) => test.toJson()).toList());
      debugPrint("data: $jsonOutput");
      return Text(jsonOutput);
    }

    // 无数据情况
    return const Text('暂无数据');
  },
)

额外说明

如果只是想让Test实例的toString输出更友好(非严格JSON),也可以在Test类中重写toString()方法:

@JsonSerializable() 
class Test {
  int? id;
  String? image;
  Test({this.id, this.image});
  
  factory Test.fromJson(Map<String, dynamic> json) => _$TestFromJson(json);
  Map<String, dynamic> toJson() => _$TestToJson(this);

  // 重写toString
  @override
  String toString() {
    return '{"id":$id,"image":"$image"}';
  }
}

但这种方式无法处理特殊字符转义等JSON规范要求,因此更推荐使用jsonEncode的方案。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.03 03:55:16