What does it mean when you declare a constant constructor with {super.key}?

Viewed 70

I have the following bare bones code

import 'package:flutter/material.dart';

//write the main method
void main() => runApp(const MyApp());

//write the MyApp class that extends the StatelessWidget class
class MyApp extends StatelessWidget {
  //write the const ctor
  const MyApp({super.key});
  //write the build method
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
        title: 'hello',
        home: Scaffold(
          appBar: AppBar(
            title: const Text('hello'),
          ),
          body: const Center(
            child: Text('hello'),
          ),
        ));
  }
}

Note the constant constructor,

const MyApp({super.key});

I thought the curly cues {} were used for optional named parameters.

I see no name here.

What's going on? What does it mean to pass in {super.key} into a constant constructor?

2 Answers

From Dart 2.17 added a new Super initializers. See the image below for more information.

In fact, when we applied the new feature to the Flutter framework, we saw a total reduction of nearly two thousand lines of code!

enter image description here

Reference: https://medium.com/dartlang/dart-2-17-b216bfc80c5d

What you probably know is this version:

const MyApp({this.key});

Which normally means you scoll up a bit and see a line like

final Key key;

This is called initializing formal parameters. Now, in this specific case with the Key, your own widget having that key doesn't do much, you have to make sure the Widget super class that is somewhere in your inheritance tree knows about it, so Flutter can use it for it's logic.

So what you did in the past is this:

const MyApp({Key? key}) : super(key: key);

That means you get an optional Key named key and then you pass it directly to the super class.

Since Dart 2.17 this has been shortened. Like the syntax for filling in your own fields, that says this.key as constructor parameter means this parameter goes directly into the given field, super.key now means that parameter goes directly into the super class constructor. So for the same code above, we end up with the code you are looking at:

const MyApp({super.key});

To quote the Dart guide on it:

To avoid having to manually pass each parameter into the super invocation of a constructor, you can use super-initializer parameters to forward parameters to the specified or default superclass constructor.

It's in the tour, but you have to scroll a little, it doesn't have it's own anchor I could link to.

Related