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

Dart中同名不同作用域变量如何指定访问目标变量?

Dart中访问被局部变量遮蔽的全局变量

假设在Dart(DartPad)中有如下代码:

String a = "I am higher in the scope chain";

void main() {
  String a = "I am lower in the scope chain, but I have the same name";
  print(a);
}

有没有关键字可以让我们打印父作用域中的变量?比如尝试用print(parent.a)或者print(this.a),但这两种写法都无法生效。


在Dart里,没有专门的关键字能直接引用被局部变量遮蔽的全局变量,不过可以通过两种方式绕开这个问题:

  • 将全局变量封装到类的静态成员中,通过类名访问:

    class Global {
      static String a = "I am higher in the scope chain";
    }
    
    void main() {
      String a = "I am lower in the scope chain, but I have the same name";
      print(Global.a); // 输出全局作用域的a
    }
    
  • 给当前库添加前缀,通过前缀访问全局变量:

    import 'dart:core' as self; // 单文件中可导入自身库并指定前缀
    
    String a = "I am higher in the scope chain";
    
    void main() {
      String a = "I am lower in the scope chain, but I have the same name";
      print(self.a); // 输出全局作用域的a
    }
    

补充说明:

  • this在这里无效,因为main是顶级函数,顶级作用域中this为null,且局部变量不属于任何对象实例,无法通过this关联到全局变量。
  • Dart本身没有parent这类指向父作用域的关键字。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.09 16:10:42