在 Dart 中直接将实例属性打印到控制台的正确语法(不仅仅是打印范围内的变量)

Boo*_*unz 1 printing variables string-interpolation dart flutter

在 Dart/Flutter 中,假设您有一个Class Y的实例a

Y类有一个属性property1

您想使用字符串插值来打印该属性,如下所示:

print('the thing I want to see in the console is: $a.property1');
Run Code Online (Sandbox Code Playgroud)

但是你甚至不能在没有错误的情况下完成输入。

我可以让它工作的唯一方法是这样做:

var temp = a.property1;
print ('the thing I want to see in the console is: $temp');
Run Code Online (Sandbox Code Playgroud)

我还没有在网上找到答案……我认为必须有一种方法可以直接做到这一点,而不必先创建变量。

小智 6

您需要将属性括在花括号中:

print('the thing I want to see in the console is: ${a.property}');
Run Code Online (Sandbox Code Playgroud)

然后将打印 a.property 的值。