How can I add Navigation to GridView from InkWell Class

Viewed 165

I created a GridView Widget and added a simple Navigation to InkWell widget. I want to go to every different page when pressing different GridTiles, but I have created my GridView like this :

 Widget _buildGrid(BuildContext context) => GridView.extent(
      maxCrossAxisExtent: 150,
      padding: const EdgeInsets.all(4),
      mainAxisSpacing: 4,
      crossAxisSpacing: 4,
      children: _buildGridTileList(30, context));

  List<Widget> _buildGridTileList(int count, BuildContext context) =>
      List.generate(
        count,
        (i) => InkWell(
          onTap: () => Navigator.of(context).push(
            MaterialPageRoute(
              builder: (context) =>
                  ParaScreen(), //you can pass the index (i) in the constructor of YourWidget(i) something like this if needed
            ),
          ),
          child: Container(
            decoration: BoxDecoration(border: Border.all(color: Colors.black)),
            child: Image.asset('images/pic$i.jpg'),
          ),
        ),
      );
}

So, as you can see that the grids are created like List.generate, Note: I have tried to pass the index but it isn't working out too well.

Thanks

1 Answers

You can add a function that return differrent page when it has the different index, the function may look like this:

    Widget _pageByIndex(int index){
      switch(index){
      case 0:{
       return Page1(); // page that should be navigated to when chose the GridTile number 1 
   
} 
      case 1: {
      return Page2();
    }
    //you can add as much cases as you want
    }
    } 

And then add it to your onTap callback like this:

onTap: () => Navigator.of(context).push(
            MaterialPageRoute(
              builder: (context) =>
                 _pageByIndex(index),
            ),
          ),
Related