0

I'm teaching myself Dart and Flutter, and I'm having a look at the example app that is loaded when you generate a fresh Dart project in IntelliJ.

The first line of the MyHomePage class is confusing me, I'm not actually sure what it is doing. Obviously the call to super is passing the key to the inherited class, which makes me think the MyHomePage call is the constructor of the class.

But then the {Key key, this.title}, is creating an object with a key and title variable, where exactly is it getting key from? Is it automatically injecting the value of title in this object to the final string title below it?

If someone could explain this line I'd appreciate it.

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key, this.title}) : super(key: key);

  // This widget is the home page of your application. It is stateful, meaning
  // that it has a State object (defined below) that contains fields that affect
  // how it looks.

  // This class is the configuration for the state. It holds the values (in this
  // case the title) provided by the parent (in this case the App widget) and
  // used by the build method of the State. Fields in a Widget subclass are
  // always marked "final".

  final String title;

  @override
  _MyHomePageState createState() => _MyHomePageState();
}
user9754798
  • 363
  • 3
  • 15

1 Answers1

0

These are optional parameters when you want to pass a parameter to a class at creation, you will put a variable of your preference

final String title;

and you can pass it as a parameter when creating an object

_MyHomePageState(title : 'hello world');

Keep in mind these are named optional parameters you can ignore them if you like as the example used none of them.

_MyHomePageState();//no parameters passed.

and for more kinds of parameters such as named, optional and others check this link

Henok
  • 3,293
  • 4
  • 15
  • 36