Home > Back-end >  Flutter error encounter 'The argument type 'int' can't be assigned to the parame
Flutter error encounter 'The argument type 'int' can't be assigned to the parame

Time:07-18

enter image description here Encounter an error

(The argument type 'int' can't be assigned to the parameter type 'CardItem'.) at line 'itemBuilder: (context, index) => buildCard(item: index,),'

enter image description here

CodePudding user response:

You need to pass CardItem object instead of index becuase required is CardItem not index

You need to make

List<CardItem> cartItems=
[
CartItem();
CartItem();
];

Then you need pass in your ListView as cartItems[index] In your case you have to pass your _items List as _items[index] to ListView.builder

CodePudding user response:

You mean that you wanna use cardItems right?

I think you make a typo, because of name of the list cardItems. then you should pass it in the itembuilder : like this

buildCard(cardItems[index]);

CodePudding user response:

Firstly you extracted Widget to method which named buildCard. This approach is not recommended by Flutter. To learn more why:

https://dartcodemetrics.dev/docs/rules/flutter/avoid-returning-widgets

https://iiro.dev/splitting-widgets-to-methods-performance-antipattern/

The best way which Flutter recommends is extract Widgets to Stateful or Stateless widget classes. In the upper link.

For your code.

  1. Extract your returned Widget to Stateless or Stateful widget

  2. Give CartItem to the constructor of your created CardWidget to use CardWidget inside it data.

  3. Then your item builder must be like this: itemBuilder: (context, index) => MyCustomCardWidget(item: _items[index]),

  4. Your MyCustomCardWidget must be like this:

class MyCustomCardWidget extends StatelessWidget {
  final CartItem item;
  const MyCustomCardWidget({Key? key, required this.item}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Container(child: Text(item.name), ....yourwidget code here);
  }
}
  • Related