Responsive design in Flutter: solved exercise with LayoutBuilder and MediaQuery

Responsive design in Flutter: solved exercise with LayoutBuilder and MediaQuery

A Flutter app runs on mobile (360 dp), tablet (768 dp), and desktop (1280 dp). Without responsive design, the same screen that looks great on iPhone appears broken on iPad. Flutter provides three main tools to adapt to available space: MediaQuery, LayoutBuilder, and OrientationBuilder.

Problem statement

Implement a news app that:

  • On mobile: shows a vertical list of cards.
  • On tablet/landscape: shows a list on the left and the detail on the right (master-detail).
  • On desktop: adds a side navigation rail.
  • Uses LayoutBuilder for internal layouts and MediaQuery for adaptive typography and padding.

Dependencies

Flutter SDK only.

Full solution

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
import 'package:flutter/material.dart';

void main() => runApp(const MaterialApp(home: NewsApp()));

// ── Model ──────────────────────────────────────────────────────────────────────
class Article {
  final int id;
  final String title;
  final String category;
  final String body;
  final Color color;

  const Article({
    required this.id,
    required this.title,
    required this.category,
    required this.body,
    required this.color,
  });
}

const _articles = [
  Article(
    id: 1, category: 'Technology', color: Colors.blue,
    title: 'Flutter 4.0 arrives with native AI support',
    body: 'The Flutter team has announced version 4.0, which includes native '
        'integration with language models, improved ahead-of-time compilation, '
        'and full Impeller support across all platforms.',
  ),
  Article(
    id: 2, category: 'Design', color: Colors.purple,
    title: 'Material You becomes the de facto standard',
    body: 'Two years after its introduction, Material You has consolidated as '
        'the preferred design system for Android and iOS developers. '
        'Its dynamic color system reduces design time by 40%.',
  ),
  Article(
    id: 3, category: 'Backend', color: Colors.green,
    title: 'Dart on the server: benchmarks vs Node.js',
    body: 'A comparative study shows that Dart on the server with the Shelf '
        'framework outperforms Node.js in HTTP request throughput by 23%, '
        'with lower memory consumption.',
  ),
  Article(
    id: 4, category: 'Community', color: Colors.orange,
    title: 'FlutterConf 2026 surpasses 10,000 attendees',
    body: 'The annual Flutter conference breaks its historical attendance record. '
        'The most demanded topics were AI, Impeller, and the new incremental '
        'compilation system.',
  ),
  Article(
    id: 5, category: 'Open Source', color: Colors.teal,
    title: 'Riverpod 4.0 simplifies state management',
    body: 'The latest version of Riverpod eliminates the need to generate code '
        'with build_runner for most use cases, reducing boilerplate '
        'by 60% according to its authors.',
  ),
];

// ── Breakpoints ────────────────────────────────────────────────────────────────
class Breakpoints {
  static const double mobile = 600;
  static const double tablet = 900;
  static const double desktop = 1200;

  static bool isMobile(double width) => width < mobile;
  static bool isTablet(double width) => width >= mobile && width < desktop;
  static bool isDesktop(double width) => width >= desktop;
}

// ── Root app ───────────────────────────────────────────────────────────────────
class NewsApp extends StatefulWidget {
  const NewsApp({super.key});
  @override
  State<NewsApp> createState() => _NewsAppState();
}

class _NewsAppState extends State<NewsApp> {
  int _selectedIndex = 0;
  Article? _selectedArticle;

  @override
  Widget build(BuildContext context) {
    // MediaQuery.sizeOf is more efficient than MediaQuery.of(context).size
    // (only rebuilds when size changes, not on every MediaQuery change)
    final width = MediaQuery.sizeOf(context).width;

    return Scaffold(
      body: Breakpoints.isDesktop(width)
          ? _DesktopLayout(
              selectedIndex: _selectedIndex,
              onIndexChanged: (i) => setState(() => _selectedIndex = i),
              selectedArticle: _selectedArticle,
              onArticleSelected: (a) => setState(() => _selectedArticle = a),
            )
          : _MobileTabletLayout(
              width: width,
              selectedArticle: _selectedArticle,
              onArticleSelected: (a) => setState(() => _selectedArticle = a),
            ),
      bottomNavigationBar: Breakpoints.isMobile(width)
          ? NavigationBar(
              selectedIndex: _selectedIndex,
              onDestinationSelected: (i) => setState(() => _selectedIndex = i),
              destinations: const [
                NavigationDestination(icon: Icon(Icons.article), label: 'News'),
                NavigationDestination(icon: Icon(Icons.bookmark), label: 'Saved'),
                NavigationDestination(icon: Icon(Icons.person), label: 'Profile'),
              ],
            )
          : null,
    );
  }
}

// ── Mobile / tablet layout ─────────────────────────────────────────────────────
class _MobileTabletLayout extends StatelessWidget {
  final double width;
  final Article? selectedArticle;
  final ValueChanged<Article> onArticleSelected;

  const _MobileTabletLayout({
    required this.width,
    required this.selectedArticle,
    required this.onArticleSelected,
  });

  @override
  Widget build(BuildContext context) {
    final isTablet = Breakpoints.isTablet(width);

    if (isTablet && selectedArticle != null) {
      return Row(
        children: [
          SizedBox(
            width: 360,
            child: _ArticleList(
              onArticleSelected: onArticleSelected,
              selectedId: selectedArticle!.id,
            ),
          ),
          const VerticalDivider(width: 1),
          Expanded(child: _ArticleDetail(article: selectedArticle!)),
        ],
      );
    }

    if (isTablet) {
      return Row(
        children: [
          SizedBox(
            width: 360,
            child: _ArticleList(onArticleSelected: onArticleSelected),
          ),
          const VerticalDivider(width: 1),
          const Expanded(
            child: Center(child: Text('Select an article')),
          ),
        ],
      );
    }

    return _ArticleList(
      onArticleSelected: (article) {
        Navigator.push(
          context,
          MaterialPageRoute(builder: (_) => _ArticleDetail(article: article)),
        );
      },
    );
  }
}

// ── Desktop layout ─────────────────────────────────────────────────────────────
class _DesktopLayout extends StatelessWidget {
  final int selectedIndex;
  final ValueChanged<int> onIndexChanged;
  final Article? selectedArticle;
  final ValueChanged<Article> onArticleSelected;

  const _DesktopLayout({
    required this.selectedIndex,
    required this.onIndexChanged,
    required this.selectedArticle,
    required this.onArticleSelected,
  });

  @override
  Widget build(BuildContext context) {
    return Row(
      children: [
        NavigationRail(
          selectedIndex: selectedIndex,
          onDestinationSelected: onIndexChanged,
          labelType: NavigationRailLabelType.all,
          destinations: const [
            NavigationRailDestination(icon: Icon(Icons.article), label: Text('News')),
            NavigationRailDestination(icon: Icon(Icons.bookmark), label: Text('Saved')),
            NavigationRailDestination(icon: Icon(Icons.person), label: Text('Profile')),
          ],
        ),
        const VerticalDivider(width: 1),
        SizedBox(
          width: 400,
          child: _ArticleList(
            onArticleSelected: onArticleSelected,
            selectedId: selectedArticle?.id,
          ),
        ),
        const VerticalDivider(width: 1),
        Expanded(
          child: selectedArticle != null
              ? _ArticleDetail(article: selectedArticle!)
              : const Center(child: Text('Select an article')),
        ),
      ],
    );
  }
}

// ── Article list ───────────────────────────────────────────────────────────────
class _ArticleList extends StatelessWidget {
  final ValueChanged<Article> onArticleSelected;
  final int? selectedId;

  const _ArticleList({required this.onArticleSelected, this.selectedId});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('Flutter News')),
      body: LayoutBuilder(
        builder: (context, constraints) {
          final hPadding = constraints.maxWidth > 500 ? 24.0 : 12.0;
          return ListView.separated(
            padding: EdgeInsets.symmetric(horizontal: hPadding, vertical: 12),
            itemCount: _articles.length,
            separatorBuilder: (_, __) => const SizedBox(height: 8),
            itemBuilder: (_, i) {
              final article = _articles[i];
              final isSelected = article.id == selectedId;
              return _ArticleCard(
                article: article,
                isSelected: isSelected,
                onTap: () => onArticleSelected(article),
              );
            },
          );
        },
      ),
    );
  }
}

class _ArticleCard extends StatelessWidget {
  final Article article;
  final bool isSelected;
  final VoidCallback onTap;

  const _ArticleCard({
    required this.article,
    required this.onTap,
    this.isSelected = false,
  });

  @override
  Widget build(BuildContext context) {
    return Card(
      color: isSelected
          ? Theme.of(context).colorScheme.primaryContainer
          : null,
      child: InkWell(
        onTap: onTap,
        borderRadius: BorderRadius.circular(12),
        child: Padding(
          padding: const EdgeInsets.all(12),
          child: Row(
            children: [
              CircleAvatar(
                backgroundColor: article.color.withOpacity(0.2),
                child: Icon(Icons.article, color: article.color),
              ),
              const SizedBox(width: 12),
              Expanded(
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    Text(article.category,
                        style: TextStyle(
                            color: article.color,
                            fontSize: 11,
                            fontWeight: FontWeight.w600)),
                    Text(article.title,
                        maxLines: 2,
                        overflow: TextOverflow.ellipsis,
                        style: const TextStyle(fontWeight: FontWeight.bold)),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

// ── Article detail ─────────────────────────────────────────────────────────────
class _ArticleDetail extends StatelessWidget {
  final Article article;
  const _ArticleDetail({required this.article});

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        final isWide = constraints.maxWidth > 600;
        final hPadding = isWide ? constraints.maxWidth * 0.1 : 24.0;
        final titleSize = isWide ? 28.0 : 22.0;

        return Scaffold(
          appBar: AppBar(title: Text(article.category)),
          body: SingleChildScrollView(
            padding: EdgeInsets.symmetric(horizontal: hPadding, vertical: 24),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                Container(
                  height: isWide ? 240 : 160,
                  decoration: BoxDecoration(
                    color: article.color.withOpacity(0.15),
                    borderRadius: BorderRadius.circular(16),
                  ),
                  child: Center(
                    child: Icon(Icons.article, size: isWide ? 80 : 60,
                        color: article.color),
                  ),
                ),
                const SizedBox(height: 24),
                Text(article.title,
                    style: TextStyle(
                        fontSize: titleSize, fontWeight: FontWeight.bold)),
                const SizedBox(height: 16),
                Text(article.body,
                    style: TextStyle(
                        fontSize: isWide ? 16 : 14, height: 1.6)),
              ],
            ),
          ),
        );
      },
    );
  }
}

When to use each tool

ToolWhen to use it
MediaQuery.sizeOf(context)Global app breakpoints (mobile/tablet/desktop)
LayoutBuilderAdapt a widget to the space provided by its parent
OrientationBuilderChange layout when the device rotates
AspectRatioMaintain a fixed proportion regardless of size
FractionallySizedBoxDimensions as a percentage of the parent
Flexible / ExpandedDistribute space in Row/Column

Common mistakes

  • MediaQuery.of(context).size instead of MediaQuery.sizeOf: the old version rebuilds the widget on any MediaQuery change (rotation, keyboard, status bar), not just size changes. Use sizeOf from Flutter 3.10+.
  • Hardcoded breakpoints in multiple places: centralize breakpoints in a class or constants to maintain consistency.
  • Not testing on tablet with Flutter DevTools: the web desktop emulator is the fastest way to test multiple sizes. Enable responsive mode with Ctrl+Shift+M in Chrome.

Practical use

Responsive design is mandatory if your app targets Play Store + iPad (App Store) + web. The same Flutter code can adapt to all of them if you use LayoutBuilder and breakpoints from the start.

Guided practice and next step

FAQ

Does Flutter have an official AdaptiveScaffold?

Yes. The flutter_adaptive_scaffold package (from the Flutter team) provides an AdaptiveScaffold that automatically uses BottomNavigationBar on mobile, NavigationRail on tablet, and NavigationDrawer on desktop. It’s a good foundation to avoid reinventing the wheel.

Should I use MediaQuery or LayoutBuilder for an adaptive grid?

LayoutBuilder. An adaptive grid depends on the space given by its parent widget, not the full screen size. LayoutBuilder gives you the exact available BoxConstraints.

Does Flutter Web require more responsive work than mobile?

Yes, the size range is wider (320 dp to 4K) and users resize windows. Plan from the start with LayoutBuilder and min/max widths for content containers.