Home > database >  Create a new Object Instance of Existing object dart
Create a new Object Instance of Existing object dart

Time:08-19

So I basically have following problem in my code:

I have a set to that I add my Object:

  ProductInstance p = ProductInstance("name", 3);

  products.add(p);

then I modify the object & and execute a method with it:

   p.zahl = 5;

  addProduct(p);

The methods then prints both values out and because of Object References its the same :/

addProduct(ProductInstance product) {
  ProductInstance? temp;

  if (products.isNotEmpty) {
    for (var element in products) {
      if (true) {
        temp = element;
      }
    }
    if (temp != null) {
      print(temp.zahl);
      print(product.zahl);
    }
  }

  if (products.isEmpty) {
    products.add(product);
  }
}

So what I want to do is to pass a new Instance of the existing p in my method without a lot of refactoring. What can I do?

Full Code to achieve same behaviour:

main() {
  ProductInstance p = ProductInstance("name", 3);

  products.add(p);

  p.zahl = 5;

  addProduct(p);
}

Set products = {};

class ProductInstance {
  String name;
  int zahl;

  ProductInstance(this.name, this.zahl);
}

addProduct(ProductInstance product) {
  ProductInstance? temp;

  if (products.isNotEmpty) {
    for (var element in products) {
      if (true) {
        temp = element;
      }
    }
    if (temp != null) {
      print(temp.zahl);
      print(product.zahl);
    }
  }

  if (products.isEmpty) {
    products.add(product);
  }
}

CodePudding user response:

When using the = operator on two objects they are both going to point to the same object.

Also when you change the value inside with p.zahl = 5; you are also changing its value inside the set of products. I do not fully understand what you want to do but here is a way you can print 2 different values. You will also need to declare a setter value , as depicted below

main() {
  ProductInstance p = ProductInstance("name", 3);

  products.add(p);
  //p.zahl = 5; dont change the value here

  addProduct(p);
}

Set products = {};

class ProductInstance {
  String name;
  int zahl;

  set setZahl(int k) {
    zahl = k;
  }

  ProductInstance(this.name, this.zahl);
}

addProduct(ProductInstance product) {
  ProductInstance? temp;

  if (products.isNotEmpty) {
    for (var element in products) {
      if (true) {
        temp = ProductInstance(element.name, element.zahl  2); //create a new object
        
      }
    }
    if (temp != null) {
      print(temp.zahl);
      print(product.zahl);
    }
  }

  if (products.isEmpty) {
    products.add(product);
  }
}
  • Related