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

Dart同一类内不同方法间变量传递实现及代码问题排查

Dart类内方法传值问题修复

问题根因

你的代码存在4个导致结果不符合预期的问题:

  • 构造函数赋值无效:构造函数仅声明了name入参,不存在名为l的入参,this.l = l本质是把默认值为null的类属性l赋值给自己,没有完成有效初始化。
  • 执行顺序逻辑矛盾:代码是逐行同步执行的,你先调用greet()读取购买数量,再调用purchase()计算数量赋值给l,调用greet时purchase还未运行,不可能拿到后续才会计算的值,自然输出null。
  • 字符串拼接遗漏:传入自定义姓名调用greet时,问候语Hello $name末尾缺少你期望的感叹号。
  • 方法逻辑顺序不合理:你需要同时满足「计算购买数量→输出问候语→打印商品列表」的输出顺序,就不能把商品打印逻辑放在purchase方法的最前面,也不能在外部提前单独调用greet。

修正后完整代码

class Customer{
  String? name;
  int? l;

  Customer(String? name){
    this.name = name;
    // 初始化购买数量默认值为0
    this.l = 0;
  }

  // 增加可选的自定义姓名入参,方便调用时直接传入
  void purchase(List<String> args, [String? customGreetName]){
    // 第一步先计算购买数量,赋值给类属性供greet读取
    int l = args.length;
    this.l = l;
    // 第二步先输出问候语
    if(customGreetName != null){
      greet(customGreetName);
    }else{
      greet();
    }
    // 第三步最后打印购买的商品列表
    for(int i = 0;i<l;i++){
      print(args[i]);
    }
  }

  void greet([name = 'none']){
    if(name != 'none'){
      // 补全感叹号匹配期望输出
      print('Hello $name!');
      print('$name, you purchased ${this.l} item(s)');
    }
    else{
      print('Hello!');
      print('${this.name}, you purchased ${this.l} item(s)');
    }
  }
}

void main(){
  Customer customer_1 = Customer("Sam");
  customer_1.purchase(["chips", "chocolate", "orange juice"]);
  print("-----------------------------");
  Customer customer_2 = Customer("David");
  customer_2.purchase(["orange juice"], "David");
}

运行结果

执行上述代码后将完全匹配你期望的输出:

Hello!
Sam, you purchased 3 item(s)
chips
chocolate
orange juice
-----------------------------
Hello David!
David, you purchased 1 item(s)
orange juice

如果你需要保留外部单独调用greet的写法,必须保证调用greet的代码写在purchase调用之后,否则永远拿不到正确的购买数量。如果同时需要问候语排在商品列表前面,把purchase方法内打印商品的逻辑移到greet调用之后即可。

内容的提问来源于stack exchange,提问作者Md. Rezuwan Hassan

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.30 19:36:33