Dart 如何正确使用构造函数?

戳这里了解《Flutter入门与实战》专栏,持续更新、系统学习!

前言

Dart 语言的构造函数和其他语言会有些不同,我们列举一下 Dart 中的构造函数的几种形式。

// 最常见的形式
class Person {
  String name;
  int age;
  Person(this.name, this.age);
}

// 命名构造函数
class Person {
  late String name;
  late int age;

  Person.fromJson(Map<String, dynamic> json) {
    name = json['name'];
    age = json['age'];
  }
}

// 工厂构造函数
class Person {
  late String name;
  static final Map<String, Person> _cache =
      <String, Person>{};

  factory Person.withName(String name) {
    return _cache.putIfAbsent(
        name, () => Person._internal(name));
  }
  
  Person._internal(this.name);
}

// 常量构造函数
class Person {
  final String name;
  final int age;
 
  const Person(this.name, this.age);
}

// 使用其他构造函数构造
class Person {
  String name;
  int age;
	
  Person(this.name, this.age);
  Person.anymous(int age): this('Anymous', age);
}

// 带参数断言的构造函数(debug 模式有效)
class Person {
  String name;
  int age;
  Person.withAssert(this.name, this.age)
      : assert(age >= 0),
        assert(name.length > 0);
}

// 使用父类构造函数构建
class Student extends Person {
  String school;
  Student(name, age, this.school) : super(name, age);
}

这里比较容易混淆的是命名构造函数工厂构造函数。实际上工厂构造函数的特点是不一定返回新的实例,比如我们示例的代码,可以从缓存中取出已有对象返回。同时,工厂构造函数还可以返回该类的子类。而且工厂构造函数是要通过 return 语句返回一个对象,而命名构造函数不允许返回,只能构建当前类的对象。这么多构造函数,该如何合理使用,我们来看看官方的指引规范。

规则1:尽可能使用构造函数直接初始化成员的方式

Dart 提供了一种快捷初始化成员属性的方式,那就是在构造函数中使用 this.语法,这时候对应的成员会自动赋值而无需手动进行赋值。这样的初始化成员的方式更加简洁。

// 正确示例
class Point {
  double x, y;
  Point(this.x, this.y);
}

// 错误示例
class Point {
  double x, y;
  Point(double x, double y)
      : x = x,
        y = y;
}

规则2:如果构造函数会初始化成员,那么不要使用 late 修饰。

声明式 null safety 要求非空字段必须在使用之前被初始化。由于成员属性可能在构造函数中使用,因此如果不初始化非空成员的话,会导致编译器报错。可以通过在成员前加 late 修饰,这时候如果不初始化而直接使用该成员的话 ,会将编译时错误转换为运行时错误。这种情况下最好的解决办法是为构造函数提供成员清单进行初始化。

// 正确示例
class Point {
  double x, y;
  Point.polar(double theta, double radius)
      : x = cos(theta) * radius,
        y = sin(theta) * radius;
}

// 错误示例
class Point {
  late double x, y;
  Point.polar(double theta, double radius) {
    x = cos(theta) * radius;
    y = sin(theta) * radius;
  }
}

使用初始化清单的形式的好处是在使用这些成员之前能够确保已经得到了初始化,哪怕是构造函数中。我们可以理解为是一种语法糖,在构造函数最开始处对这些成员进行了初始化。

规则3:对于空构造函数体,使用分号结束而不是{}空函数体

在 Dart 中,如果构造函数体为空,那么可以简单地用分号结束函数,而无需使用大括号来写一个空的函数体。

// 正确示例
class Point {
  double x, y;
  Point(this.x, this.y);
}

//错误示例
class Point {
  double x, y;
  Point(this.x, this.y) {}
}

规则4:不要使用 new 来构建新对象

Dart 2版本以后,new 关键字是可选的。new 关键字实际上在 Dart 中已经被标记为弃用了。当你习惯了没有 new 的方式后,你肯定会和我一样,觉得加了 new 关键字的代码很丑陋,尤其是在组件树中。

// 正确示例
Widget build(BuildContext context) {
  return Row(
    children: [
      RaisedButton(
        child: Text('Increment'),
      ),
      Text('Click!'),
    ],
  );
}

// 错误示例
Widget build(BuildContext context) {
  return new Row(
    children: [
      new RaisedButton(
        child: new Text('Increment'),
      ),
      new Text('Click!'),
    ],
  );
}

规则5:不要加多余的 const

当一个对象在上下文中必须是常量时,const 关键字是隐式的,而无需再单独写。下面列举的上下文中的表达式是默认就是 const 的:

  • 一个不变的集合;
  • 调用声明为 const 的构造函数;
  • 元数据的注解;
  • 用于常量声明时的初始化对象(见下面的示例)
  • switch-case 语句中的 case 冒号后面的表达式。
// 正确示例
const primaryColors = [
  Color('red', [255, 0, 0]),
  Color('green', [0, 255, 0]),
  Color('blue', [0, 0, 255]),
];

// 错误示例
const primaryColors = const [
  const Color('red', const [255, 0, 0]),
  const Color('green', const [0, 255, 0]),
  const Color('blue', const [0, 0, 255]),
];

基本上,在 Dart 2中,如果一个对象前面加 new 来替代 const 会报错的话,那么就隐式是 const 的,此时无需再额外加 const

总结

Dart 语言为我们提供了很多简写构造函数的语法糖,虽然按其他语言那种形式编写也不会有什么问题,但是遵循旧的方式如何能够体现 Dart 这门年轻语言的优势呢?因此,多了解 Dart 语言自身的一些特性,可以让我们的编码效率更高,代码更整洁。

猜你喜欢

转载自blog.csdn.net/shuijian00/article/details/124638857
今日推荐