Home > Back-end >  How does spread operator work in Flutter?
How does spread operator work in Flutter?

Time:07-17

I am following a Flutter tutorial that I can't understand this part:

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};
  }
}

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();
}

I can't understand what _items look like? Also ..._items and {..._items}?

Generally I can't understand the difference between these 3 variables and how each of them look like?

CodePudding user response:

... represents content of set or list
for example:

var list = [1,2,3,4];
var newList = [...list, 5] //eqals to [1,2,3,4,5]
var newNewList = [list] //syntax error

and ... inside curly brace means it assigns its values as json object's elements.

[
  {
    "id": existingCartItem.id,
    "title": existingCartItem.title,
    "price": existingCartItem.price,
    "quantity": existingCartItem.quantity   1,
  },
  {
    ...
  },
]

CodePudding user response:

_items is declared here:

Map<String, CartItem> _items = {};

..._items is used only in {..._items}, which is creating a new Map. The contents of the Map come from creating a list that consists of key:value pairs (entries) from the current contents of _items, and in precisely the right shape that they will essentially end up as a "shallow copy" of the original data. This is to protect the value being returned from being mutated to affect the original data.

For details, look at the feature specification for spreads (and collection literal if/for), and the motivation behind it.

  • Related