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

Flutter中Script类toString返回实例标识而非文本内容问题求助

问题分析与解决方法

问题出在Dart自定义类的默认toString()行为:你定义的Script类没有重写toString()方法,当你尝试将Script实例转为字符串时,Dart会调用默认的toString(),返回固定格式的"Instance of Script",而不是你期望的text属性值。

解决方法有两种,按需选择:

  1. 重写Script类的toString()方法
    在model文件夹的Script类中添加如下代码,让它直接返回text属性:
class Script {
  final String text;

  Script(this.text);

  // 重写toString方法
  @override
  String toString() {
    return text;
  }
}

之后再调用scripts[0].toString()(或直接隐式转字符串),就能得到text的内容。

  1. 直接访问text属性
    在界面代码中,不要直接使用scripts[0],而是明确访问它的text属性:
// 复制时用这个
String targetText = scripts[0].text;

这种方式更直观,也避免了重写toString可能带来的其他潜在影响。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.03 10:30:54