Home > Software design >  gridview's all buttons should be fit inside its parent container in flutter
gridview's all buttons should be fit inside its parent container in flutter

Time:11-07

I am trying to make UI of calculator based on my drawing,

here I have divided screen in two expanded container, top one for output and bottom one for buttons...

in bottom container I have taken grid view to show all buttons,

I want to fit all button's in bottom area without having scrolling effect of grid view.

in my code...grid view not showing last row...I have to scroll down to view it...

enter image description here here is my code

Widget build(BuildContext context) {
    return Scaffold(
      body: SafeArea(
        child: Column(
          children: [
            Expanded(child: Container(color: Colors.orange,)),
            Expanded(
                child: GridView.builder(
                  itemCount: buttons.length,
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 4),
                    itemBuilder: (context, index) {
                      return ButtonWidget(color: Colors.grey,
                          ontap: () {},
                          caption: buttons[index].toString(),
                          textcolor: Colors.black);
                    })),
          ],
        ),
      ),
    );
  }

and here is button's class


class ButtonWidget extends StatelessWidget {
  final color;
  final textcolor;
  final String caption;
  final VoidCallback ontap;

  const ButtonWidget(
      {Key? key,
      required this.color,
      required this.ontap,
      required this.caption,
      required this.textcolor})
      : super(key: key);

  @override
  Widget build(BuildContext context) {
    return Padding(
      padding: const EdgeInsets.all(8.0),
      child: Container(
        decoration: BoxDecoration(
          color: Colors.grey[400],
          borderRadius: BorderRadius.circular(100),
        ),
        child: Center(
            child: Text(
          caption.toString(),
          style: GoogleFonts.actor(fontSize: 30,fontWeight: FontWeight.bold),
        )),
      ),
    );
  }
}


CodePudding user response:

1.Remove your Expanded for GridView.

  1. Disable scrolling for GridView. Like this.

       GridView.builder(
        /// Add these two lines
         shrinkWrap: true,
         physics: const NeverScrollableScrollPhysics(),
         /// Your code,
        ),
    

Tip: If you don't wanna have small container on top, you can resize buttons' aspect ratio like this. But it will make buttons look a bit ugly.

gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 4,
///Add this, tweak the value as you wish
childAspectRatio: 1.3,
),

Have Fun!

  • Related