Blogs By Shankar
Dart
Dart
  • Dart Tutorial by Dès Vu Technologies
  • hello
  • Dart Collection
    • collectionInDart
  • File Handeling
    • fileHandelingInDart
  • Functions
    • functionParameters
    • Types of Functions in Dart
    • Functions in Dart
    • Annonymous Function
      • AnnonymousFunction
    • Arrow Function
      • arrowFunctions
    • BuiltinFunctions
      • importantBuiltinFunctions
      • mathFunction
  • OOP With Dart
    • encapsulation
    • oopWithDart
    • Generic In Dart
      • generic
    • constructor
      • constructor
      • factory constructor
        • factoryConstructor
      • initializer list constructor
        • Initializer List Constructor:
    • async dart
      • asyncAndAwait
        • asyncAndAwait
      • future
        • future
      • streams
        • streams
  • Sync and Async dart
    • syncAndAsyncDart
  • controlFlow
    • controlFlow
  • dataTypes
    • Dart Built-In Data Types
    • TypeConversion
    • String
      • stringOperations
      • string_jnterpolation
    • operators
      • Operators In Dart
  • operators
    • operators
  • user_input
    • userInput
  • variablesAndConstants
    • scopeInDart
    • variableTypesInDart
    • variables
Powered by GitBook
On this page
  1. OOP With Dart
  2. constructor
  3. initializer list constructor

Initializer List Constructor:

An initializer list constructor is a type of constructor in Dart that allows you to perform additional initialization of fields before the constructor's body runs. It is useful when you need to set up fields with specific values or perform other calculations before the constructor's logic is executed.

Key characteristics of initializer list constructors:

  • Initialization Before Constructor Body: The initializer list is executed before the constructor's body, ensuring that field initialization happens early in the object creation process.

  • Use of Colon (:): To define an initializer list constructor, use a colon (:) followed by field assignments and other initializations.

Here's an example of an initializer list constructor:

Copy code
class Point {
  final int x;
  final int y;

  // Initializer list constructor
  Point(this.x, this.y) : assert(x >= 0), assert(y >= 0);
}

void main() {
  var point = Point(2, 3);
  print('Point: ${point.x}, ${point.y}'); // Output: Point: 2, 3
}

In this example:

  • The Point class has two final fields, x and y, which are set in the initializer list.

  • The assert statement is used to check that x and y are non-negative values. If the assertions fail, it will throw an error.

Initializer list constructors are particularly useful for setting up the initial state of objects and validating input values before constructing an object. They ensure that field initialization is done correctly and efficiently.

Previousinitializer list constructorNextasync dart

Last updated 1 year ago