Static In Dart

Static In Dart :

Static In Dart

Static In Dart

  • Static members (functions or properties) are available on the class itself, instead of on an instance of that class.
  • Static methods cannot be overridden.
  • Static methods & variables are variables whose declarations are immediately contained within a class declaration and that are declared static.

Static Variable :

class Adder {
  static int added = 0;
  
  static int add(int number) { // (I'd suggest overriding the + operator)
    return added += number;
  }
}

void main() {
  print(Adder.add(2)); // 2 
  print(Adder.add(3)); // 5
  print(Adder.add(5)); // 10
}

static variable which can be accessed using the class name space :

class Location {
  static int accessCount = 0; 
  
  num _lat, _lng;
  
  Location(num lat, num lng) {
    _lat = lat;
    _lng = lng;
    accessCount++;
  }

  String toString() => "${_lat}, ${_lng} accessCount($accessCount)";
}

void main() {
  var waikiki = new Location(21.271488, -157.822806);
  print(waikiki); // 21.271488, -157.822806 accessCount(1)
  
  var hometown = new Location(48.19366, -122.12681);
  print(hometown); // 48.19366, -122.12681 accessCount(2)
  
  var london = new Location(51.50403, -0.11844);
  print(london); // 51.50403, -0.11844 accessCount(3)
  
  print("Current Location AccessCount is ${Location.accessCount}");

Static Method :

static functions allows you to encapsulate or group functions in a class.
class StringUtils {
  static String removeUnderscores(String string) {
     return string.replaceAll("_", " ");
  }
  
  static int countAs(String string) {
    int total = string.length;
    int diff = string.replaceAll("A", "").length;
    return total - diff;
  }
}

void main() {
  print(StringUtils.removeUnderscores("I_went_to_the_store.")); // I went to the store.
  
  print(StringUtils.countAs("Apple abe Able Mable Arc At")); // 4
}

Constant Instances
Use the const keyword to define a constant.

Objects can be compile time instances, created at compile time and accessed statically with the Location class.
class Location {
  static final WAIKIKI = const Location(21.271488, -157.822806); // Compile time instances
  static final HOMETOWN = const Location(48.19366, -122.12681); 
  static final LONDON = const Location(51.50403, -0.11844);
  
  final num lat, lng; // Instance variables
  
  const Location(this.lat, this.lng);
  
  toString() => "Have you been to ${lat},${lng}?";
}

void main() {
  print(Location.WAIKIKI); // Using the constants
  print(Location.HOMETOWN);
  print(Location.LONDON);
}

The flutter tutorial  is a website that bring you the latest and amazing resources of code. All the languages codes are included in this website. The languages like flutter, android, java,kotlin etc.with the help of this languages any user can develop the beautiful application

For more information about Flutter. visit www.fluttertutorial.in