Dart Extension Methods and Use of Getter/Setter


Dart Extension Methods and Usage of Getter/Setter

The Dart programming language offers software developers the possibility to write flexible and readable code thanks to the concepts of extension methods and getter/setter. Especially in Flutter and Dart-based projects, it is very important to take advantage of these two features to make the code more sustainable and modular.

What are Dart Extension Methods?

Extension methods are a powerful feature introduced in Dart 2.7 that allow you to add extra functions to existing classes, interfaces, or data types. With Dart extension methods, you can easily define new functionalities in third-party classes or classes you have written yourself. This enriches and makes your code more readable without altering existing classes.

Example of Dart Extension Methods

extension StringExtensions on String {
  String capitalize() => this.isNotEmpty
      ? this[0].toUpperCase() + this.substring(1)
      : '';
}

void main() {
  String name = 'ali';
  print(name.capitalize()); // Output: Ali
}

Usage of Dart Getter and Setter

The Dart programming language provides controlled access to a class's properties through the getter and setter methods. Getter functions handle reading the value of a variable, while setter functions allow you to perform custom operations before assigning the value. In this way, the encapsulation principle of object-oriented programming is applied.

Example of Dart Getter and Setter

class Student {
  String _name = '';

  String get name => _name;

  set name(String value) {
    if (value.length > 2) {
      _name = value;
    } else {
      throw Exception('Name must be at least 3 characters long!');
    }
  }
}

void main() {
  var stu = Student();
  stu.name = 'Ayşe';
  print(stu.name); // Output: Ayşe
}

Conclusion

The use of Dart extension methods and getter/setter makes your code more functional, readable, and secure. Especially in medium and large-scale projects, it is recommended to utilize these structures both for adding functionality and ensuring data security. Taking advantage of these modern features in your Dart programming projects will increase the efficiency of your development process.