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 = '';
}
}