Super Constructor Example

Dart 2.17 于 2022 年 5 月 5 日发布,这个新版本带来了一些漂亮的变化。其中之一是 Super Constructor (超级构造器) 功能,它可以让我们在编写构造器时更轻松,并进一步缩短代码。

新旧对比

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
class Animal {
  final String name;
  final double age;

  const Animal({ required this.name, required this.age });
}

class Budgie extends Animal {
  // 旧的语法
  const Budgie({ required String name, required double age })
      : super(name:name, age:age);

  // 新的语法
  const Budgie({ required super.name, required super.age });
}

实际应用

这里以改造 Flutter 官方 Center 组件为例。

1
2
3
4
5
6
7
8
class Center extends Align {
  // 改造前
  const Center({ Key? key, double? widthFactor, double? heightFactor, Widget? child })
    : super(key: key, widthFactor: widthFactor, heightFactor: heightFactor, child: child);

  // 改造后
  const Center({ super.key, super.widthFactor, super.heightFactor, super.child });
}

完整实例

前往 DartPad 查看效果:https://dartpad.dev/?id=e75b493dae1287757c5e1d77a0dc73f1

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import 'package:flutter/material.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      title: 'Super Constructor Demo',
      debugShowCheckedModeBanner: false,
      home: Material(
        child: CustomCenter(
          child: Text(
            'Super Constructor Demo',
          ),
        ),
      ),
    );
  }
}

class CustomCenter extends Align {
  // 改造前
  //const Center({ Key? key, double? widthFactor, double? heightFactor, Widget? child })
  //  : super(key: key, widthFactor: widthFactor, heightFactor: heightFactor, child: child);

  // 改造后
  const CustomCenter(
      {super.key, super.widthFactor, super.heightFactor, super.child});
}

番外

最常见的应用场景就是用来把 XXX({ Key? key }): super(key: key); 精简为 XXX({ super.key })小小的改动,大大的能量。

相关内容

参考资料

Licensed under CC BY-NC-SA 4.0