‘MyhomePage({Key key, this.title}) : super(key: key);’ in Flutter – what would be a clear explanation with an example?

The code is the constructor of the MyHomepage widget.

{Key key, this.title}

It declares two optional named parameters (optional named because of {}) where

  • the first is of name key with type Key

  • the second is of name title with the type of the field this.title and automatically initializes this.title with the passed value. This is nice syntactic sugar that saves some writing.

: starts the initializer list.
The initializer list allows some to execute some expressions before the call is forwarded to the constructor of the super class.

When a class is initialized, read access to this is forbidden until the call to the super constructor is completed (until the body of the constructor is executed – in your example the constructor has no body).

The initializer list is often use to validate passed parameter values with assert(key != null) or to initialize final fields with calculated values (final fields can’t be initialized or updated later).

super(key: key) forwards to the constructor of the super class and passes the parameter key passed to MyHomepage to the super constructors key parameter (same as for MyHomepage({Key key})).

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)