I installed Awesome Flutter Snippets and Flutter Snippets extension in VS Code. When I install these two extensions, I can use some keyboard shortcuts to generate widgets.
When I type statelessW
or stless
in the code and hit enter, it generates StatelessWidget
like this:
statelessW
:
class name extends StatelessWidget {
const name({super.key});
@override
Widget build(BuildContext context) {
return Container();
}
}
stless
:
class MyWidget extends StatelessWidget {
const MyWidget({super.key});
@override
Widget build(BuildContext context) {
return Container();
}
}
You can see that the above two pieces of code are the same, the two pieces of code use ({super.key});
instead of ({Key? key}) : super(key: key);
.
Is it recommended to use ({super.key});
instead of ({Key? key}) : super(key: key);
in Flutter? I would appreciate any help. Thank you in advance!
this is the new feature since Dart 2.17 - just a shorthand that achieves the same thing.
More details here: https://codewithandrea.com/tips/dart-2.17-super-initializers/
I'll just copy/paste an exmample from the link above:
Old syntax:
class Person {
Person(this.name);
final String name;
}
// Old way: before Dart 2.17
class Employee extends Person {
Employee(String name, this.salary) : super(name);
final int salary;
}
New syntax:
// New way: Dart 2.17 and above
class Employee extends Person {
Employee(super.name, this.salary);
final int salary;
}
Works for named arguments, too:
class Person {
Person({required this.name});
final String name;
}
// New way: Dart 2.17 and above
class Employee extends Person {
Employee({required super.name, required this.salary});
final int salary;
}