1

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!

My Car
  • 4,198
  • 5
  • 17
  • 50

1 Answers1

6

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;
}
Andrija
  • 1,534
  • 3
  • 10
  • Hi, thanks for your answer. While this link may answer the question, it's better to include the essential parts of the answer here and provide a link for reference. Link-only answers may become invalid if the linked page changes. – My Car Nov 22 '22 at 08:27
  • 1
    Good point, I edited my answer with details from the link. – Andrija Nov 22 '22 at 08:33
  • Ok, I have accepted and upvoted this answer – My Car Nov 22 '22 at 08:35