Reputation: 23
When I refactored my Widget in Flutter the following code is generated. However, I still do not understand what is it for and why is it there. I deleted it and nothing broke. Everything is okay. What is it for?
const ReusableCard({
Key key,
}) : super(key: key);
This is the complete class that was refactored:
class ReusableCard extends StatelessWidget {
const ReusableCard({
Key key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Container(
margin: EdgeInsets.all(15),
decoration: BoxDecoration(
color: Color(0xFF1D1E33),
borderRadius: BorderRadius.circular(10.0),
),
);
}
}
Upvotes: 0
Views: 541
Reputation: 3768
As stated in Dart Language tour:
Subclasses don’t inherit constructors from their superclass. A subclass that declares no constructors has only the default (no argument, no name) constructor. [...] By default, a constructor in a subclass calls the superclass’s unnamed, no-argument constructor.
So, in your example, deleting this constructor would call the default constructor of the Stateless Widget class. We can see from the documentation of this class that a optional parameter named key may be passed to it. The ReusableCard
constructor you are asking is allowing you to create a Stateless Widget using this key parameter. If you delete this constructor, you won't be able to give this Widget a Key.
A Key is an identifier for Widgets and other elements in the Flutter framework. It is needed in some situations where you must identify the widget. The most common example for this is when you try to swap (or delete) Widgets in a list. To recognize they changed Flutter framework needs the key to identify them. If you are not doing any of these cases, or if you're not using keys at all, it's ok to delete this constructor.
A great official video from Google about keys in Flutter can be seen here.
Upvotes: 1