How to Initialize Variables in Constructor Body In Dart

A constructor is a special type of method that is called when you create a new instance of a class. The constructor is responsible for initializing the state of the object.

In Dart, you can initialize variables in the constructor body by 3 methods.

  • Init a variable’s value on the declaration
  • Use a semi-colon to assign values to variables
  • Use late keyword
class Task {
    String title = '';
    String description = '';

    Task(this.title, this.description) {

    }
}
class Task {
    String title = '';
    String description = '';

    Task(this.title, this.description) {

    }
}
class Task {
    String title;
    String description;

    Task(this.title, this.description) : title = 'Daily task',  description = 'Need to finish today'{

    }
}
class Task {
    late String title;
    late String description;

    Task(this.title, this.description){
        title = 'Fix Flutter errors';  
        description = '';
    }
}

By continuing to use the site, you agree to the use of cookies. more information

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.

Close