arraysflutterlistdartreference-type

Does the myList.where() method in Dart use reference type?


Creating my Flutter app, I am using Dart obviously.

Now, something confuses me very much coming from other programming languages:

import 'dart:developer'; // so that inspect works

// List<Product> allProducts = [
//   Product(
//     purchaseType: PurchaseType.HOUSE,  // enum type
//     someId: null  // String? type
//   ),
//   Product(
//     purchaseType: PurchaseType.CAR, // enum type
//     someId: null  // String? type
//   )
// ];

List<Product> updateProduct = allProducts.where((p) {
    return (p.purchaseType == PurchaseType.HOUSE);
}).toList();

inspect(allProducts);
updateProduct[0].someId = "1234";
inspect(allProducts);

Please note that I inspect allProducts (i.e. the original List that I do not intend to mutate actually)!

The first inspect log of allProducts looks like this:

[0] Product
  purchaseType = HOUSE
  someId = null
[1] Product
  purchaseType = CAR
  someId = null

The second inspect log of allProducts looks like this:

[0] Product
  --> purchaseType = HOUSE
  --> someId = 1234     // !!!!!!!!!!!!!!!!!!!
[1] Product
  --> purchaseType = CAR
  --> someId = null

WHY is the allProducts list mutated now ???

Is the `myList.where() method creating a reference type in Dart ???

If yes, how can I improve my code so that allProducts is not mutated and I can get a full copy of it ?


Solution

  • Both lists refer to the same objects. You will need to make a deep copy for it to work. By the way this works like this in many (most?) object-oriented programming languages. Dart is no exception. You could do something like this to make it work

    List<Product> updateProduct = allProducts.map((p)=>p.copy()).where((p) {
        return (p.purchaseType == PurchaseType.HOUSE);
    }).toList();
    

    And then add a copy() method to the Product that returns a copy of itself