Dart Super Constructor 应用实例(Dart 2.17 新特性)
Dart 2.17 于 2022 年 5 月 5 日发布,这个新版本带来了一些漂亮的变化。其中之一是 Super Constructor (超级构造器)
功能,它可以让我们在编写构造器时更轻松,并进一步缩短代码。
新旧对比
1class Animal {
2 final String name;
3 final double age;
4
5 const Animal({ required this.name, required this.age });
6}
7
8class Budgie extends Animal {
9 // 旧的语法
10 const Budgie({ required String name, required double age })
11 : super(name:name, age:age);
12
13 // 新的语法
14 const Budgie({ required super.name, required super.age });
15}
实际应用
这里以改造 Flutter 官方 Center
组件为例。
1class Center extends Align {
2 // 改造前
3 const Center({ Key? key, double? widthFactor, double? heightFactor, Widget? child })
4 : super(key: key, widthFactor: widthFactor, heightFactor: heightFactor, child: child);
5
6 // 改造后
7 const Center({ super.key, super.widthFactor, super.heightFactor, super.child });
8}
完整实例
前往 DartPad 查看效果:https://dartpad.dev/?id=e75b493dae1287757c5e1d77a0dc73f1
1import 'package:flutter/material.dart';
2
3void main() => runApp(MyApp());
4
5class MyApp extends StatelessWidget {
6 @override
7 Widget build(BuildContext context) {
8 return const MaterialApp(
9 title: 'Super Constructor Demo',
10 debugShowCheckedModeBanner: false,
11 home: Material(
12 child: CustomCenter(
13 child: Text(
14 'Super Constructor Demo',
15 ),
16 ),
17 ),
18 );
19 }
20}
21
22class CustomCenter extends Align {
23 // 改造前
24 //const Center({ Key? key, double? widthFactor, double? heightFactor, Widget? child })
25 // : super(key: key, widthFactor: widthFactor, heightFactor: heightFactor, child: child);
26
27 // 改造后
28 const CustomCenter(
29 {super.key, super.widthFactor, super.heightFactor, super.child});
30}
番外
最常见的应用场景就是用来把 XXX({ Key? key }): super(key: key);
精简为 XXX({ super.key })
。小小的改动,大大的能量。