Flutter: Select Card inside GridView

2,043

You can use Gridview.builder and use its index to get the related object from list:

return GridView.builder(
        gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
        physics: ScrollPhysics(),
        itemCount: _customCards.length,
        itemBuilder: (BuildContext context, int index){
         return Inkwell(child:_customCards(
          imageUrl: image[index], item: item[index], price: price[index], count: count[index]),
          onTap(){
            print(tops[index]);
           }
        ),
        }
        );*
Share:
2,043
Alex Ali
Author by

Alex Ali

Updated on December 22, 2022

Comments

  • Alex Ali
    Alex Ali over 1 year

    I have an app which displays data in Cards inside GridView like so:

    GridView.count(
              crossAxisCount: 2,
              children: <Widget>[
                _customCard(
                  imageUrl: image1, item: item1, price: price1, count: count1
                ),
                _customCard(
                  imageUrl: image2, item: item2, price: price2, count: count2
                ),
                _customCard(
                  imageUrl: image3, item: item3, price: price3, count: count3
                ),
                _customCard(
                  imageUrl: image4, item: item4, price: price4, count: count4
                ),
              ],
            ),
    

    I want to get the specified card name when it is pressed depending on its index inside a List as we do in ListView.

     class item {
      final String name;
      final int count;
      final String imageUrl;
      final double price;
    
      item({this.name, this.imageUrl,  this.count, this.price});
    }
    
    List<item> tops = [
      new item(
          imageUrl: "tshirt.png",
          name: "T-shirt",
          count: 0,
          price: 0.50
      ),
      new item(
          imageUrl:   "shirt.png",
          name: "Shirt",
          count: 0,
          price: 0.80
      ),
    

    Is there a way to do so with GridView or shall I try something else?

  • Alex Ali
    Alex Ali almost 4 years
    Thank you it worked as I wanted..I appreciate your help