How To Create Grid To Pager Using Flutter Android App

admin_img Posted By Bajarangi soft , Posted On 27-11-2020

When a user clicks a GridView card, we set isPageViewVisible to true.When a user presses the back button, if the pageView is visible, we set the flag to false.PageView is always on top of the GridView.

How To Create Grid To Pager Using Flutter Android App

Grid To Pager 
Complete Code For Grid To Pager In Flutter
main.dart

import 'package:flutter/material.dart';
void main(){
  runApp(MyApp());
}

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
    // TODO: implement build
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {
  MyHomePage({Key key}) : super(key: key);

  @override
  _MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
  List<String> images = [
    'img1.jpg',
    'img2.jpg',
    'img3.jpg',
    'img4.jpg',
    'img5.jpg',
    'img6.jpg',
    'img7.jpg',

  ];
  bool isPageViewVisible = false;

  @override
  Widget build(BuildContext context) {
    return WillPopScope(
      onWillPop: () async {
        if (isPageViewVisible) {
          _setPageViewVisible(false);
          return false;
        }
        return true;
      },
      child: Scaffold(
        backgroundColor: Colors.black,
        appBar: AppBar(
          backgroundColor: Colors.deepPurple,
            title: Text('Grid To Pager')),
        body: Stack(
          children: <Widget>[
            _buildGridView(),
            _buildPageView(),
          ],
        ),
      ),
    );
  }

  Widget _buildGridView() {
    return GridView.count(
      crossAxisCount: 2,
      children: images.map((imageName) {
        return GestureDetector(
          onTap: () => _setPageViewVisible(true), //<--- on GridView item click, show PageView
          child: Card(
            child: Center(
              child: Image.asset("assets/images/$imageName",),
            ),
          ),
        );
      }).toList(),
    );
  }

  Widget _buildPageView() {
    PageView pageView = PageView.builder(
      itemCount: images.length,
      itemBuilder: (context, index) {
        return Center(
          child: Image.asset("assets/images/${images[index]}"),
        );
      },
    );

    return Opacity(
      opacity: isPageViewVisible ? 1 : 0,
      child: IgnorePointer(
        ignoring: !isPageViewVisible,
        child: pageView,
      ),
    );
  }

  void _setPageViewVisible(bool visible) {
    setState(() => isPageViewVisible = visible);
  }
}

Related Post