Home > Net >  How do I get Dart Flutter GridView items to click?
How do I get Dart Flutter GridView items to click?

Time:02-24

I'm trying to make an interface with Dart Flutter. I made an interface like this:

enter image description here

I want these items to be clickable. When clicked, I will take action. What can I do so that items can be clicked?

Codes:

body: Center(
        child: GridView.builder(
          gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
            crossAxisCount: 2,
          ),
          itemCount: subjects.length,
          itemBuilder: (BuildContext context, int index) {
            return Container(
              child: Card(
                child: Column(
                  mainAxisAlignment: MainAxisAlignment.center,
                    children: [
                      Image.asset(subjects[index].subjectImage, fit: BoxFit.cover, height: 50, width: 50,),
                      SizedBox(height: 10,),
                      Text(subjects[index].subjectName, style: TextStyle(fontSize: 20),),
                    ],
                  ),
                ),
            );
          },
        ),
      )

CodePudding user response:

You can use GestureDetector or Inkwell for this.And write your onpress action code in onTap().

     GestureDetector(
    onTap: () {
      // To do
    },
    child: Card(
     
    ),
  ),

or

InkWell(
    onTap: () {
      // To do
    },
    child: Card(),
  ),

CodePudding user response:

You can use GestureDetector or Inkwell for Press your any Widget in flutter using onTap() function

GestureDetector(
    onTap: () {
      // Write your code here
    },
    child: Container(),
  ),

or use inkwell like

 InkWell(
        onTap: () {
          // Write your code here
        },
        child: Container(),
      ),

CodePudding user response:

Try this- GestureDetector or InkWell is useful for your case...

  body: Center(
            child: GridView.builder(
              gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
                crossAxisCount: 2,
              ),
              itemCount: subjects.length,
              itemBuilder: (BuildContext context, int index) {
                return GestureDetector(
     onTap: () {
          // call click event
        },
     child: Container(
                  child: Card(
                    child: Column(
                      mainAxisAlignment: MainAxisAlignment.center,
                        children: [
                          Image.asset(subjects[index].subjectImage, fit: BoxFit.cover, height: 50, width: 50,),
                          SizedBox(height: 10,),
                          Text(subjects[index].subjectName, style: TextStyle(fontSize: 20),),
                        ],
                      ),
                    ),
    ),
                );
    
              },
            ),
          )
  • Related