Search code examples
variablesprintingflutterdartstring-interpolation

Proper Syntax When Using dot Operator in String Interpolation in Dart


In Dart/Flutter, suppose you have an instance a of Class Y.

Class Y has a property, property1.

You want to print that property using string interpolation like so:

print('the thing I want to see in the console is: $a.property1');

But you can't even finish typing that in without getting an error.

The only way I can get it to work is by doing this:

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

I haven't found the answer online... and me thinks there must be a way to just do it directly without having to create a variable first.


Solution

  • You need to enclose the property in curly braces:

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

    That will then print the value of a.property.