Home > Blockchain >  How is each element in the Grid View navigated to a specific page in Flutter?
How is each element in the Grid View navigated to a specific page in Flutter?

Time:11-23

I have 3 pages the first one is home_page, page1, and page2 the home_page has GridView which is retrieve the data from a List which has 2 elements, so my GridView now will display 2 item like this image

home_page

And I make InkWell() for my Card() widget to be clickable.

So, when I click on page1 item I want to navigate to page1 screen also if I click on page2 item I want to navigate to another screen which is page2 screen. I used onTap(){} but always goes to page1

my InkWell method:

InkWell gridItem(Category category) {
      return InkWell(
        child: Card(
          shape:
              RoundedRectangleBorder(borderRadius: BorderRadius.circular(10)),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Container(
                //color: Colors.green,
                width: 100,
                height: 100,
                padding: const EdgeInsets.all(8),
                child: Image.asset(category.image),
              ),
              Text(
                category.name,
                style: const TextStyle(fontSize: 18),
              ),
            ],
          ),
        ),
        onTap: () {
          Navigator.push(context, MaterialPageRoute(builder: (context) {
            return const Page1(); 
          }));
        },
      );
    }

How I achieve this goal, thank you.

Edit:

class Category {
  late String name;
  late String image;

  Category({required this.name, required this.image});
}

CodePudding user response:

You simply need to determine the page related to the category.

So, instead of directly set the page to always to Page1() like this:

onTap: () {
  Navigator.push(context, MaterialPageRoute(builder: (context) {
    return const Page1(); 
  }));
},

change it to something like this:

onTap: () {
   _goToPage(category.id); // or category number 
                           // or anything to differentiate each item of category
},

with _goToPage(int number) method:

void _goToPage(int number) {

   Widget page;

   // You can also use if else here.
   switch(number) {
     case 0:
       page = Page1();
     break;
     case 1:
       page = Page2();
     break;
     default:
       page = Page1(); // default item when no matching category found
   }

   Navigator.push(context, MaterialPageRoute(builder: (context) {
        return page; 
      }));
}
  • Related