Reputation: 641
I am getting this error: Too many positional arguments: 0 expected, but 3 found. (extra_positional_arguments_could_be_named at itemBuilder...and can not figure out what could be causing it.
the error is appearing here ->
itemBuilder: (ctx, i) => ProductItem(
loadedProducts[i].id,
loadedProducts[i].title,
loadedProducts[i].imageUrl,
),
class ProductListPage extends StatelessWidget {
ProductListPage({this.context});
final List<Product> loadedProducts = [
Product(
id: 'p1',
title: "Michael Kora",
description: 'this is cool',
price: 699,
imageUrl:
"https://n1.sdlcdn.com/imgs/c/9/8/Lambency-Brown-Solid-Casual-Blazers-SDL781227769-1-1b660.jpg",
),
Product(
id: 'p1',
title: "Michael Kora",
description: 'this is cool',
price: 699,
imageUrl:
"https://n1.sdlcdn.com/imgs/c/9/8/Lambency-Brown-Solid-Casual-Blazers-SDL781227769-1-1b660.jpg",
),
];
final BuildContext context;
// @override
Widget build(BuildContext context) {
return Scaffold(
body: GridView.builder(
padding: const EdgeInsets.all(10.0),
itemCount: loadedProducts.length,
itemBuilder: (ctx, i) => ProductItem(
loadedProducts[i].id,
loadedProducts[i].title,
loadedProducts[i].imageUrl,
),
);
}
}
ProductItem
is defined as follows:
class ProductItem extends StatelessWidget {
ProductItem({this.id, this.imageUrl, this.title});
final String id;
final String title;
final String imageUrl;
@override
Widget build(BuildContext context) {
return GridTile(
child: Image.network(imageUrl),
);
}
}
Upvotes: 0
Views: 1663
Reputation: 3091
Short answer:
ProductItem
expects named, not positional arguments. Initialize it like so:
ProductItem(
id: loadedProducts[i].id,
title: loadedProducts[i].title,
imageUrl: loadedProducts[i].imageUrl,
)
Longer answer:
The error informs us:
Too many positional arguments: 0 expected, but 3 found.
Which suggests that ProductItem
constructor did not expect positional arguments. It does not know what to do with them. Why? Let's inspect ProductItem
class definition:
class ProductItem extends StatelessWidget {
ProductItem({this.id, this.imageUrl, this.title});
...
}
The parameters are enclosed in {}
. In Dart, this means that they are optional named parameters. That is, if you decide to pass them in, you must pass them in like so:
ProductItem(id: 'id', imageUrl: 'url', title: 'title')
Note that each argument is preceded by its name - hence it is called a named parameter. In contrast, positional arguments are differentiated only by the position they take in a call to a constructor.
Class definition informs us that constructor of ProductItem
should not be called with positional arguments. Instead, named arguments should be used. ProductItem
should be constructed this way:
ProductItem(
id: loadedProducts[i].id,
title: loadedProducts[i].title,
imageUrl: loadedProducts[i].imageUrl,
)
To read more about types of parameters, refer to Dart documentation. Alternatively, explore the differences in DartPad.
Upvotes: 2