How to Create Getters and Setters in Dart

Getters and setters are used to access and update the value of a variable, respectively. In Dart, they have generated automatically when you create a new instance of a class.

To create a getter and a setter, simply use the keyword get and set followed by the name of the variable. You can also create getters and setters that perform more complex actions. For example, you could create a setter that only allows the value of a variable to be updated if it meets certain criteria.

class StockPicking {
  int? id;
  String? name;
  String? origin;
  double? price;

  StockPicking({,, this.origin, this.price});

  String get stateValue {
    Map<String, String> values = {
      "draft": "Draft",
      "cancel": "Cancelled",
      "waiting": "Waiting Another Operation",
      "confirmed": "Waiting Availability",
      "partially_available": "Partially Available",
      "available": "Available",
      "allocated": "Lot Allocated",
      "assigned": "Ready for Transfer",
      "done": "Transferred"
    return values.containsKey(state!) ? values[state!].toString() : state!;

  bool get isAllocated {
    return state! == 'allocated';

  set exchangedPrice(double rate){
    price = price*rate;


Getters and setters are often used in conjunction with each other. For example, you might use a setter to validate the value of a variable before it is updated. Or, you might use a getter to perform some kind of calculation based on the value of a variable.

In general, getters and setters are used to encapsulate data in a class. By hiding the implementation details of how data is stored and accessed, you can make your code more robust and easier to maintain.

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

The cookie settings on this website are set to "allow cookies" to give you the best browsing experience possible. If you continue to use this website without changing your cookie settings or you click "Accept" below then you are consenting to this.