-2

I have a simple Dart file:

class Person {
  String name;
  int age;
}

void main() {
  var person1 = Person();
  person1.name = 'Rajesh';
  person1.age = 20;
  print("person name $person1.name ");
  print(person1.name);
}

I just want to print print("person name $person1.name ");, and i want output as person name Rajesh. But i am getting output as person name Instance of 'Person'.name.

Need some help, i am new to Dart. `

raju
  • 6,448
  • 24
  • 80
  • 163

3 Answers3

2

You have to use this:

print("person name ${person1.name} ");

alternatively you can override toString in class:

  @override
  String toString() {
    return '''
            person name $name
        ''';
  }

then:

print(person1);
BeHappy
  • 3,705
  • 5
  • 18
  • 59
1

You probably meant:

print("person name: ${person1.name} ");

Remember that you can specify a toString() method in the class:

class Person {
  String name;
  int age;
  String toString() => "${name} is ${age} years old"; 
}

and use it as follows:

class Person {
  String name;
  int age;
  String toString() => "${this.name} is ${this.age} years old"; 
}

void main() {
Person person = new Person();
person.name = "John";
person.age = 25;
print(person); // John is 25 years old
}
Stefano Amorelli
  • 4,553
  • 3
  • 14
  • 30
0

Here, the error is in the interpolation string. In general, when you use more than one object, you should use the full form of the string interpolation ${} rather than just $.

For your code, do this instead:

print('person name : ${person1.name}');

I hope that will be useful to you.

Kab Agouda
  • 6,309
  • 38
  • 32