RIyal
RIyal

Reputation: 35

How can i add onTap listener in card view in flutter

I am new in flutter. In my application, I fetch the data from URL and view it. Now I want to add onTap listener which will pass the id to the function. Any idea how can I do it.

return GridView.builder(
              gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
              itemCount:snapshot.data.length,
              itemBuilder:(BuildContext context, int index) {
                final x = snapshot.data[index];
                return Card(
                  child: Column(
                    children: <Widget>[
                      Image.network(
                        'https://thegreen.studio/ecommerce/default/upload/' +x.Image,
                        width: 200.0,
                        height: 150.0,
                        fit: BoxFit.cover,
                      ),
                      Text(x.Description),
                      Text("Price: RM:134"),

                    ],
                    

                  ),
                );
              },
            );

Upvotes: 1

Views: 613

Answers (2)

Akif
Akif

Reputation: 7640

@BeHappy is right. You can use GestureDetector to listen to the onTap function. You can pass the id of the indexed item into your method. It will look like this:

return GridView.builder(
  gridDelegate:
      SliverGridDelegateWithFixedCrossAxisCount(crossAxisCount: 2),
  itemCount: snapshot.data.length,
  itemBuilder: (BuildContext context, int index) {
    final x = snapshot.data[index];
    return GestureDetector(
      onTap: () {
        // You can pass the id of indexed item.
        yourMethod(x.id);
      },
      child: Card(
        child: Column(
          children: <Widget>[
            Image.network(
              'https://thegreen.studio/ecommerce/default/upload/' + x.Image,
              width: 200.0,
              height: 150.0,
              fit: BoxFit.cover,
            ),
            Text(x.Description),
            Text("Price: RM:134"),
          ],
        ),
      ),
    );
  },
);

Upvotes: 0

BeHappy
BeHappy

Reputation: 3978

You can wrap Card widget with GestureDetector:

GestureDetector(
    onTap: () {
      // Code
    },
    child: Card(
        ...
    ),
)

Upvotes: 1

Related Questions