Usage of extensions in Flutter


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.


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]'));

Answered By – Ghanshyam Bhesaniya

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published