[Solved] Usage of extensions in Flutter


Asked by Edoardo on December 07, 2021 (source).

I am sorry for the question, but I am new to Flutter. I usually code in swift, and I use the UIKit framework. Sometimes it is really useful to add an extension to a Class, in which I add functions related to that Class in order to have a clean code.

Is it correct/professional to use extensions in Flutter?

For example:

extension on _MapViewScreenState {
  double calculateDistance(lat1, lon1, lat2, lon2) {
    var p = 0.017453292519943295;
    var c = cos;
    var a = 0.5 -
        c((lat2 - lat1) * p) / 2 +
        c(lat1 * p) * c(lat2 * p) * (1 - c((lon2 - lon1) * p)) / 2;
    return 12742 * asin(sqrt(a));

  // Other functions

This extension contains functions that _MapViewScreenState uses.


Question answered by Ghashyam B (source).

The feature named Extension methods, Introduced in Dart 2.7 allows us to add new functionality to already available libraries. Although it does not allow us to modify existing code directly, It gives us the ability to customize a class in a way that we can read and use it easily.

We can also write an extension for getters, setters, and operators as well, these are called Extension members. It has been named ‘Extension methods’ so that developers coming from Kotlin, C# can also relate to it.

extension ExtendedString on String {
  bool get isValidName {
    return !this.contains(new RegExp(r'[0–9]'));