Mahmoud Nasser
Mahmoud Nasser

Reputation: 105

Is it better to pass an object or pass individual attributes of the object to widgets in flutter

for example, if we had a shop app and we use a

class Product {
  final String title;
  final String description;
  final double price;

  Product({
    @required this.title,
    @required this.description,
    @required this.price,
  });
}

and we have a ProductCard widget which uses title and price of the product

so if we have a product object like

Product product1 = Product(
  title: 'bike',
  description: 'black mountain bike',
  price: 2000.0,
);

So is it better to pass Product object to the widget like this:

ProductCard(product: product1)

or pass the attributes we need like this:

ProductCard(title: product1.title, price: product1.price)

Upvotes: 1

Views: 697

Answers (1)

Alex Collette
Alex Collette

Reputation: 1784

It really depends on the object you are passing. In this case, I think it makes more sense to pass the object, as it will get messy if you end up passing lots of individual attributes, and if you were to change the data structure, or the widget at some point, you will likely have to redo it. You are only passing a reference to the object, so it isn't less efficient to just pass the entire object.

If the object contains other objects, and does not have a finite size, like a list or map, I think it makes more sense to pass the attributes directly to the widget.

Upvotes: 3

Related Questions