Skip to main content

How to Create Extension Methods in Dart

An extension method is a static method that is defined in a class but is called as if it were an instance method on the extended type.

Extension methods were introduced in Dart 2.7 as a way to extend the functionality of existing libraries without needing an entirely new library or even knowing about these features beforehand! For example, when you use code completion in your IDE and it offers some extension method suggestions alongside other standard function definitions – that’s because they’re tracking what has been defined elsewhere. This may not be within this file, but the IDE is keeping track of all the code that has been written.

In Dart, you can create an extension method by adding the keyword “extension” before the method’s return type.

//syntax
extension <extension name> on <type> {
  (<member definition>)*
}
extension NumberFormat on String {
  int toInt() {
    return int.parse(this);
  }
}
enum DataStatus { none, add, change, remove }

extension DataStatusExtension on DataStatus {
  String get status {
    switch (this) {
      case DataStatus.add:
        return 'ADD';
      case DataStatus.change:
        return 'CHANGE';
      case DataStatus.remove:
        return 'REMOVE';
      default:
        return 'NONE';
    }
}
extension DateString on String{

  /* Print date string as dd-MM-yyyy */
  String toDate(){
    if(isEmpty) return "";

    DateFormat dateFormat = DateFormat('dd-MM-yyyy');
    var parsedDate = DateTime.parse(this).add(const Duration(hours: 8)); //add 8 to UTC to make it SGP time
    var date =  dateFormat.format(parsedDate);
    return date.contains(" ") ? date.split(" ")[0] : date;
  }

  String toDateTime(){
    if(isEmpty) return "";

    DateFormat dateFormat = DateFormat('dd-MM-yyyy').add_Hms();
    var parsedDate = DateTime.parse(this).add(const Duration(hours: 8)); //add 8 to UTC to make it SGP time
    var date =  dateFormat.format(parsedDate);
    return date;
  }
}

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