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

Dart中如何仅调用一次trim,同时赋值给final变量并传给父类构造函数?

Dart 构造函数优化:避免重复调用trim方法

方案一:利用初始化列表临时变量(Dart 2.17+)

在初始化列表中先声明临时变量存储trim后的字符串,后续同时给name和父类构造函数传参,仅调用一次trim:

class Parent {
  final List<int> bytes;
  Parent(this.bytes);
}

class Child extends Parent {
  final String name;
  
  Child(String s) 
      : final trimmed = s.trim(),
        name = trimmed,
        super(trimmed.codeUnits);
}

方案二:使用工厂构造函数(兼容所有Dart版本)

如果需要兼容低版本Dart,可通过工厂构造函数先处理字符串,再调用私有构造函数完成初始化:

class Parent {
  final List<int> bytes;
  Parent(this.bytes);
}

class Child extends Parent {
  final String name;

  // 私有构造函数
  Child._(this.name, List<int> bytes) : super(bytes);

  // 对外暴露的工厂构造函数
  factory Child(String s) {
    final trimmed = s.trim();
    return Child._(trimmed, trimmed.codeUnits);
  }
}

两种方案均能实现仅调用一次trim,同时完成name赋值与父类构造参数传递的需求。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.02 18:08:11