0

I'm building a small class just to train/learn Dart and I'm getting this error:

Error: Can't access 'this' in a field initializer to read 'firstName'.
String completeName = "${firstName} ${lastName}";
                         ^^^^^^^^^
lib/main.dart:13:41:
Error: Can't access 'this' in a field initializer to read 'lastName'.
 String completeName = "${firstName} ${lastName}";
                                       ^^^^^^^^
Error: Compilation failed.

Here is my code:

void main()
{
  var user = new User();
  user.firstName = "John";
  user.lastName = "Smith";
  user.printName();
}
​
class User
{
  String firstName;
  String lastName;
  String completeName = "$firstName $lastName";
  
  void printName()
  {
    print(completeName);
  }
}

My programming background is in C/C++ and Python and I never had a similar problem. Can anyone help me to understand why I'm getting this error? Thanks in advance! ​

  • 1
    Does this answer your question? [Dart assigning to variable right away or in constructor?](https://stackoverflow.com/questions/64546212/dart-assigning-to-variable-right-away-or-in-constructor) – jamesdlin Jan 13 '21 at 18:39

1 Answers1

0

With a getter:

void main()
{
  var user = new User();
  user.firstName = 'john';
  user.lastName = 'smith';
  user.printName();
}

class User
{
  String firstName;
  String lastName;

  User();

  String get completeName => "$firstName $lastName";

  void printName()
  {
    print(completeName);
  }
}

Or you can also do this.

void main()
{
  var user = new User("John", "Smith");
  user.printName();
}

class User
{
  String firstName;
  String lastName;
  String completeName;
  
  User(this.firstName, this.lastName) : completeName = "$firstName $lastName";
  
  void printName()
  {
    print(completeName);
  }
}
pedro pimont
  • 2,764
  • 1
  • 11
  • 24
  • 2
    And, with null safety (Dart 2.12), you can even do `late final String completeName = "$firstName $lastName";` because the value will only be computed when it's read the first time, at which point it's safe to refer to `this` and other members. (I think the getter approach is the best one when `firstName` and `lastName` are mutable). – lrn Jan 14 '21 at 12:27