पाठ 9 / 25
Responsive Layouts and Lists
MediaQuery, LayoutBuilder and ListView.builder.
Adapting to space and scrolling efficiently
MediaQuery exposes app-wide information such as screen size, padding for notches and text scale; prefer the targeted accessors like MediaQuery.sizeOf(context), which rebuild only when that property changes. LayoutBuilder gives the constraints the parent passed to this widget, which is better for reusable components that might sit in a sidebar or a full screen. Wrap content in SafeArea to avoid system intrusions. For long or unknown-length lists use ListView.builder (or ListView.separated, GridView.builder), which builds items lazily as they scroll into view; a plain ListView(children: ...) builds every child up front. For mixed scrolling effects, CustomScrollView combines slivers such as SliverAppBar and SliverList.
One list, two layouts
LayoutBuilder picks a list or a grid; items are built lazily.
class ProductsView extends StatelessWidget {
const ProductsView({super.key, required this.products});
final List<Product> products;
@override
Widget build(BuildContext context) {
return LayoutBuilder(
builder: (context, constraints) {
if (constraints.maxWidth >= 700) {
return GridView.builder(
gridDelegate: const SliverGridDelegateWithMaxCrossAxisExtent(
maxCrossAxisExtent: 280,
),
itemCount: products.length,
itemBuilder: (context, i) => ProductCard(product: products[i]),
);
}
return ListView.builder(
itemCount: products.length,
itemBuilder: (context, i) => ListTile(
title: Text(products[i].name),
subtitle: Text(products[i].price),
),
);
},
);
}
}Lists inside a Column
A ListView inside a Column has unbounded height and throws. Wrap it in Expanded, or give it a fixed height - avoid shrinkWrap: true for long lists because it builds every item.
त्वरित जाँच: Why prefer ListView.builder for a list of 10,000 items?
- It caches network images
- It sorts items automatically
- It builds items lazily as they scroll into view
- It is the only list that supports scrolling
Answer
It builds items lazily as they scroll into view — Lazy building keeps memory and build time proportional to what is visible.