In Flutter (and Dart), this line is a special form of a constructor for a widget class. Let's break it down:
1. const
This means the constructor creates a constant instance of the widget if possible. It helps Flutter optimize rendering by reusing the widget when nothing changes, which improves performance.
2. MyAppBar(...)
This is the constructor name, which matches the class name MyAppBar
. In Dart, constructors have the same name as the class.
3. {required this.title}
- The curly braces
{ }
mean these are named parameters. required
means the parameter must be provided when creating the object otherwise, you'll get a compile-time error.this.title
automatically assigns the value to the instance variabletitle
inside the class.
4. super.key
This passes the key
parameter to the parent class (in this case, StatelessWidget
or StatefulWidget
). The key
helps Flutter efficiently rebuild widgets when the widget tree changes.
Example Usage
class MyAppBar extends StatelessWidget {
final String title;
const MyAppBar({required this.title, super.key});
@override
Widget build(BuildContext context) {
return AppBar(
title: Text(title),
);
}
}
Now, when creating the app bar:
MyAppBar(title: "Home Page");
Summary
- const → Makes the widget immutable and can improve performance.
- required → Forces the parameter to be passed when creating the widget.
- this.title → Assigns the parameter directly to the class property.
- super.key → Passes the key to the parent widget for Flutter's widget tree optimization.
0 Comments:
Post a Comment