original

https://itnext.io/deep-dive-in-dart-constructors-51e4c006fb8f

refer to

text

This article discusses some tips for using Dart constructors

first

What is a constructor?

Constructors are special methods used to initialize objects. The constructor is called when an object of the class is created.

Default

 final ehe = MyClass(); // Creates an instanceclass MyClass {
  MyClass(); // Fires immediately when created (this guy is cons.)
}

There is only one rule in the constructor

That is to say;

Name it the same as its class name!!

OK, we got it! But..

What types of constructor types do we have specifically?

Default constructor ーClass()

 // Default Constructor
// 默认什么都不做
class User {
  String name = 'ehe';
  User();
}

///////////////////
// Constructor with parameters
// 构造时初始变量
class User {
  String name;
  User(this.name);
}

///////////////////
// Constructor with the initial method
// 构造函数内写入你的逻辑
class User {
  String name;
  User(this.name) {
    // do some magic
  }
}

/////////////////
// Constructor with assertion
// 使用 Asserts 去检查你的规则
class User {
  String name;
  User(this.name) : assert(name.length > 3);
}

////////////////
// Constructor with initializer
// 初始化你的变量
class User {
  static String uppercase(String e) => e.toUpperCase();
  String name;
  User(name) : name = yell(name);
  static String yell(String e) => e.toUpperCase();
}

/////////////////////
// Constructor with super()
// override 变量
class Person {
  String id;
  Person(this.id);
}
class User extends Person {
  String name;
  User(this.name, String id) : super(id);
}

/////////////////////
// Constructor with this()
// 命名构造函数
class User {
  String name;
  int salary;
  User(this.name, this.salary);
  User.worker(String name) : this(name, 10);
  User.boss(String name) : this(name, 9999999);
}

Private constructor ーClass._()

You can use _ to create a private constructor, but what's the benefit?

Let's look at an example!

 class Print {
  static void log(String message) => print(message);
}

Print.log('ehe');

// 你想写一个像这样的util,但有一个问题,因为你也可以创建一个我们不想要的实例。

Print(); // 在这种情况下,这是绝对不必要的

// 如何防止这种情况?答案是私有构造函数!

class Print {
  Print._(); // 这将阻止创建实例
  static void log(String message) => print(message);
}

Print(); // 这将给出现在的编译时错误

Your instance is safe now!

So basically you can prevent an instance from being created!

Named Constructor class.Named()

You can create instances of different types in one class

For example;

E.g:

 class User {
  String name;
  int salary;
  User.worker(this.name) : salary = 10;
  User.boss(this.name) : salary = 99999999;
}

Private named constructor ーclass._Named ()

You can easily clean your instance!

 class User {
  String name;
  int salary;
  User.worker(this.name) : salary = 10;
  User.boss(this.name) : salary = 99999999;
  User._mafia(this.name) : salary = 9999999999999;
}

Jokes aside, this is very helpful!

For example, you can create a singleton object with a private constructor!

 class User {
  User._privateConstructor();
  static final User instance = User._privateConstructor();
}

Notice

You can see _internal internal keyword in some projects. nothing special. \_internal construction is just a .\_internal name usually given to a class-private constructor (this name is not required). A private constructor can be created with any Class.\_someName structure).

Const Constructor ーconst Class()

You can use the const constructor! constructor to make a class immutable!

Constant constructors are an optimization! The compiler makes objects immutable for all Text('Hi!') objects.ーFrank Treacy
 const user = User('ehe');

class User {
  final String name;
  const User(this.name);
}

Factory constructor ーfactory class Class()

We said construction crews were not allowed to come back, guess what?

Factory builders can!

What else can factory builders do?

You don't need to create a new instance at all! You can call another constructor or subclass, or even return an instance from the cache!

Finally, a little warning to the factory!

Cannot call superclass constructor ( super() )

simple example

 class User {
  final String name;
  User(this.name);

  factory User.fromJson(Map<String, dynamic> json) {
    return User(json["name"]);
  }
}

// Singleton Example
class User {
  User._internal();
  static final User _singleton = Singleton._internal();

  factory User() => _singleton;
}

© Cat Brother

订阅号


独立开发者_猫哥
666 声望126 粉丝