What is get and set in Flutter?

As the name suggests, we use the get and set method in Flutter for security purposes. Actually to get the value of a private variable.

In our previous discussion we have seen how we can make a member variable private.

Why?

Because no one can manipulate this variable outside this class. As a result, we can use this private variable inside that class only.

However, if we need to access this variable outside that class, we can use the get method.

Dart has made it really easy to use this way.

The E commerce app, which we’ve been building from scratch, has used this get method quite often.

Look at the code below.

import 'package:flutter/foundation.dart';

class CartItem {
  final String id;
  final String title;
  final int quantity;
  final double price;

  CartItem({
    required this.id,
    required this.title,
    required this.quantity,
    required this.price,
  });
}

class Cart with ChangeNotifier {
  Map<String, CartItem> _items = {};

  Map<String, CartItem> get items {
    return {..._items};
  }

  int get itemCount {
    return _items.length;
  }

  double get totalAmount {
    var total = 0.0;
    _items.forEach((key, cartItem) {
      total += cartItem.price * cartItem.quantity;
    });
    return total;
  }

  void addItem(
    String productId,
    double price,
    String title,
  ) {
    if (_items.containsKey(productId)) {
      // change quantity...
      _items.update(
        productId,
        (existingCartItem) => CartItem(
          id: existingCartItem.id,
          title: existingCartItem.title,
          price: existingCartItem.price,
          quantity: existingCartItem.quantity + 1,
        ),
      );
    } else {
      _items.putIfAbsent(
        productId,
        () => CartItem(
          id: DateTime.now().toString(),
          title: title,
          price: price,
          quantity: 1,
        ),
      );
    }
    notifyListeners();
  }

  void removeItem(String productId) {
    _items.remove(productId);
    notifyListeners();
  }

  void clear() {
    _items = {};
    notifyListeners();
  }
}

As we see in the above code, we have used this private variable “_items” in many methods, which are public.

Besides that, we have used a get method. 

For one reason. So that we should be able to use that particular member variable elsewhere in the e-commerce app. 

The get, set method in Flutter

The get, set method in Flutter is another version of Dart code.

A Flutter developer uses dart code to build an app. Right? 

Therefore, we can see some dart code now, to understand the get and set method.

class Bear {
  // default getter and setter is set in instance variable
  int? collarID;

  //we can customize or set the color first, then get the value
  String? color;
  set setColor(String anyColor) => color = anyColor;
  String get getColor => color!;
}

void main(List<String> args) {
  var bear = Bear();
  bear.collarID = 1;
  print('Collar ID: ${bear.collarID}');
  bear.setColor = 'Brown';
  bear.getColor;
  print('Color of bear: ${bear.getColor}');
}

/**
 * Collar ID: 1
Color of bear: Brown
 */

We can customize this member variable by using the get and set method. 

However, it was unnecessary. Because if the member variable is public, in that case we don’t have to use get and set.

See another example.

Here we have used the get and set to make a private variable public.

class MyClass {
  String? _name;
  String get getName => _name!;
  set setName(String aValue) => _name = aValue;
}

main(List<String> arguments) {
  var myObject = MyClass();
  myObject.setName = "Bond, James Bond!";
  print('My name is: ${myObject.getName}');
}

// My name is: Bond, James Bond!

I hope you get the idea. 🙂

What Next?

Books at Leanpub

Books in Apress

My books at Amazon

GitHub repository

TensorFlow, Machine Learning, AI and Data Science

Twitter

Comments

One response to “What is get and set in Flutter?”

  1. […] a result, we have made it public by using the get method so that we can use them […]

Leave a Reply