Custom Grid for Special Cases
Learn to create your own custom grid when you need to adapt the number of rows and columns to the screen's width.
We'll cover the following...
In most Flutter smartphone applications, widgets that need to be repeated on the screen are often implemented using ListView
widgets. These widgets might not scale well when the same application is run on larger screens. For example, the application in the code below has a list of courses on the first screen.
import 'package:flutter/material.dart'; import 'profile_view.dart'; import 'settings_view.dart'; class AppMenu extends StatelessWidget { const AppMenu({Key? key}) : super(key: key); @override Widget build(BuildContext context) { return Container( color: Colors.white, child: SafeArea( right: false, child: Column( children: <Widget>[ _AppMenuButton( icon: const Icon(Icons.account_circle), title: 'Profile', onPressed: () { Navigator.push( context, MaterialPageRoute(builder: (context) => const ProfileView()), ); }, ), _AppMenuButton( icon: const Icon(Icons.settings), title: 'Settings', onPressed: () { Navigator.push( context, MaterialPageRoute(builder: (context) => const SettingsView()), ); }, ), ], ), ), ); } } class _AppMenuButton extends StatelessWidget { final Icon icon; final String title; final Function() onPressed; const _AppMenuButton({ Key? key, required this.icon, required this.title, required this.onPressed, }) : super(key: key); @override Widget build(BuildContext context) { return LayoutBuilder( builder: (context, constraints) { final canFitTitle = constraints.maxWidth > 180; return canFitTitle ? ListTile( leading: icon, title: Text(title), onTap: onPressed, ) : IconButton( onPressed: onPressed, icon: icon, ); }, ); } }
In course_list.dart
, we create a list of CourseView
widgets from lines 17 to 22. Because we implemented CourseView
without limiting the width of the widget, the list is going to take the entire available width. It’s too wide for larger screens.
On wider screens, such as those on tablets, we should limit the width of each CourseView
widget and fit at least two of them in a single row. We can ...