Dart initializing formal parameters

⋅ 1 min read ⋅ Flutter Dart Constructor

Table of Contents

Dart initializing formal parameters

The pattern of assigning a constructor argument to an instance variable is so common that Dart decided to add a special syntax for it.

Dart called this feature Initializing formal parameters.

To use Initializing formal parameters feature, we have to do two things:

  1. Declare a constructor by creating a function with the same name as its class.
  2. List all instance variables as constructor arguments.
    • Argument name must match an instance variable.
    • Prefix those argument with this keyword.

Here is how it looks:

class Shape {
double x;
double y;
double width;
double height;

Shape({
required this.x,
required this.y,
required this.width,
required this.height,
});
}

This will assign all arguments to respective instance variables.


Read more article about Flutter, Dart, Constructor, or see all available topic

Enjoy the read?

If you enjoy this article, you can subscribe to the weekly newsletter.
Every Friday, you'll get a quick recap of all articles and tips posted on this site. No strings attached. Unsubscribe anytime.

Feel free to follow me on Twitter and ask your questions related to this post. Thanks for reading and see you next time.

If you enjoy my writing, please check out my Patreon https://www.patreon.com/sarunw and become my supporter. Sharing the article is also greatly appreciated.

Become a patron Buy me a coffee Tweet Share
Previous
Dart Parameters

Learn three ways to declare parameters for a Dart function.

Next
CollectionView in SwiftUI with LazyVGrid and LazyHGrid

Learn the difference between a horizontal and vertical grid and everything you need to know to use them.

← Home