Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is this code writing method recommended in Flutter?

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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!

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading