0

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

1 Answer 1

2

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);
  }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.