Custom Height for Widget in GridView

Custom Height and width of grid view we can use the property ChildAspectRation of the grid view of Mobile applicaiton

Syntax 

 var size = MediaQuery.of(context).size;
 final double itemHeight =
 (size.height - kToolbarHeight - 24) / 2;
 final double itemWidth = size.width / 2;


Step-by-Step Implementation

Step 1: Create a New Project in Android Studio (File >new flutter project)


Step 2: Adding material package

Import method the runApp method in the main function call first while run the application.

 import 'package:flutter/material.dart';

 void main() {

     runApp(RunMyApp());

 }

Step 3: Creating a stateless widget

We can create a stateless widget that contains MaterialApp widget,AppBar,etc.

 class RunMyApp extends StatelessWidget {

     const RunMyApp({super.key});  

    @override

    Widget build(BuildContext context) {

    return MaterialApp(home);

     }

 }

Step 4: Custom Height for Widget in GridView

 class RunMyApp extends StatelessWidget {

     const RunMyApp({super.key});  

    @override

    Widget build(BuildContext context) {

    return MaterialApp(home);

     var size = MediaQuery.of(context).size;

     final double itemHeight =
     (size.height - kToolbarHeight - 24) / 2;

     final double itemWidth = size.width / 2;

     }

 }

Step 5: Final code 
 import 'package:flutter/material.dart';

void main() {
runApp(HomeScreen());
}

class HomeScreen extends StatefulWidget {
@override
_RunMyAppState createState() => _RunMyAppState();
}

class _RunMyAppState extends State<HomeScreen> {
List<String> widgetList = ['One', 'Two', 'Three','Four'];
@override
Widget build(BuildContext context) {
//Size of grid view
var size = MediaQuery.of(context).size;
//Height of grid view
final double itemHeight = (size.height - kToolbarHeight - 24) / 2;
//width of grid view
final double itemWidth = size.width / 2;
return Scaffold(
appBar: AppBar(
title: Text("Candidroot solutions"),
),
body: Container(
child: GridView.count(
crossAxisCount: 2,
childAspectRatio: (itemWidth / itemHeight),
controller: ScrollController(keepScrollOffset: false),
shrinkWrap: true,
scrollDirection: Axis.vertical,
children: widgetList.map((String value) {
return Container(
color: Colors.blue,
margin: EdgeInsets.all(1.0),
child: Center(
child: Text(
value,
style: TextStyle(
fontSize: 30.0,
color: Colors.white
),
),
),
);
}).toList(),
),
),
);
}
}
Step 6: Output of above example 


Happy coding!


365Bloggy June 3, 2024
Share this post
Tags
SUBSCRIBE THIS FORM


Archive