简体   繁体   中英

How to change the default property of a class from main function in Dart?

So basically what I'm trying to do is to change the default value of property for all the objects of the class.

In the image below:

图片

When I replace Person().new value with abc it doesn't change. Moreover there is no error from the compiler!!

Please help.

If you want a value to be the same across different instances of the same class, use the static keyword:

class Person {

  static var defaultName = 'Kshitij';

  String name;

  Person([this.name]){
    name ??= defaultName; // if name is null, use default name.
  }
}

Now you can change the default name to Agarwal by writing:

  Person.defaultName = 'Agarwal';

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM