Responsive design en Flutter: ejercicio resuelto con LayoutBuilder y MediaQuery

Responsive design en Flutter: ejercicio resuelto con LayoutBuilder y MediaQuery

Una app Flutter corre en móvil (360 dp), tablet (768 dp) y escritorio (1280 dp). Sin un diseño responsive, la misma pantalla que luce bien en iPhone parece rota en iPad. Flutter ofrece tres herramientas principales para adaptarse al espacio disponible: MediaQuery, LayoutBuilder y OrientationBuilder.

Enunciado

Implementa una app de noticias que:

  • En móvil: muestra una lista vertical de tarjetas.
  • En tablet/landscape: muestra una lista a la izquierda y el detalle a la derecha (master-detail).
  • En escritorio: añade un rail de navegación lateral.
  • Usa LayoutBuilder para los layouts internos y MediaQuery para tipografía y padding adaptativos.

Dependencias

Solo Flutter SDK.

Solución completa

  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
355
356
357
358
359
360
import 'package:flutter/material.dart';

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

// ── Modelo ─────────────────────────────────────────────────────────────────────
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: 'Tecnología', color: Colors.blue,
    title: 'Flutter 4.0 llega con soporte nativo de IA',
    body: 'El equipo de Flutter ha anunciado la versión 4.0, que incluye integración '
        'nativa con modelos de lenguaje, compilación anticipada mejorada y soporte '
        'completo para Impeller en todas las plataformas.',
  ),
  Article(
    id: 2, category: 'Diseño', color: Colors.purple,
    title: 'Material You ya es el estándar de facto',
    body: 'Dos años después de su introducción, Material You se ha consolidado como '
        'el sistema de diseño preferido de los desarrolladores Android e iOS. '
        'Su sistema de color dinámico reduce el tiempo de diseño un 40%.',
  ),
  Article(
    id: 3, category: 'Backend', color: Colors.green,
    title: 'Dart en el servidor: benchmarks frente a Node.js',
    body: 'Un estudio comparativo muestra que Dart en el servidor con el framework '
        'Shelf supera a Node.js en throughput de peticiones HTTP por un 23%, '
        'con menor consumo de memoria.',
  ),
  Article(
    id: 4, category: 'Comunidad', color: Colors.orange,
    title: 'FlutterConf 2026 supera los 10 000 asistentes',
    body: 'La conferencia anual de Flutter bate su récord histórico de asistencia. '
        'Los temas más demandados fueron IA, Impeller y el nuevo sistema de '
        'compilación incremental.',
  ),
  Article(
    id: 5, category: 'Open Source', color: Colors.teal,
    title: 'Riverpod 4.0 simplifica la gestión de estado',
    body: 'La última versión de Riverpod elimina la necesidad de generar código '
        'con build_runner para la mayoría de casos de uso, reduciendo el boilerplate '
        'en un 60% según sus autores.',
  ),
];

// ── 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;
}

// ── App raíz ───────────────────────────────────────────────────────────────────
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 es más eficiente que MediaQuery.of(context).size
    // (solo reconstruye al cambiar el tamaño, no ante cualquier cambio de MediaQuery)
    final width = MediaQuery.sizeOf(context).width;

    return Scaffold(
      // En escritorio mostramos NavigationRail
      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),
            ),
      // En móvil: BottomNavigationBar
      bottomNavigationBar: Breakpoints.isMobile(width)
          ? NavigationBar(
              selectedIndex: _selectedIndex,
              onDestinationSelected: (i) => setState(() => _selectedIndex = i),
              destinations: const [
                NavigationDestination(icon: Icon(Icons.article), label: 'Noticias'),
                NavigationDestination(icon: Icon(Icons.bookmark), label: 'Guardados'),
                NavigationDestination(icon: Icon(Icons.person), label: 'Perfil'),
              ],
            )
          : null,
    );
  }
}

// ── Layout móvil / tablet ─────────────────────────────────────────────────────
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) {
      // Tablet: master-detail en dos columnas
      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('Selecciona un artículo')),
          ),
        ],
      );
    }

    // Móvil: solo lista, detalle en ruta nueva
    return _ArticleList(
      onArticleSelected: (article) {
        Navigator.push(
          context,
          MaterialPageRoute(builder: (_) => _ArticleDetail(article: article)),
        );
      },
    );
  }
}

// ── Layout escritorio ──────────────────────────────────────────────────────────
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('Noticias')),
            NavigationRailDestination(icon: Icon(Icons.bookmark), label: Text('Guardados')),
            NavigationRailDestination(icon: Icon(Icons.person), label: Text('Perfil')),
          ],
        ),
        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('Selecciona un artículo')),
        ),
      ],
    );
  }
}

// ── Lista de artículos ─────────────────────────────────────────────────────────
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('Noticias Flutter')),
      body: LayoutBuilder(
        builder: (context, constraints) {
          // Padding adaptativo según el ancho disponible de ESTE widget
          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)),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

// ── Detalle del artículo ───────────────────────────────────────────────────────
class _ArticleDetail extends StatelessWidget {
  final Article article;
  const _ArticleDetail({required this.article});

  @override
  Widget build(BuildContext context) {
    // LayoutBuilder para padding y tamaño de fuente adaptativo
    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)),
              ],
            ),
          ),
        );
      },
    );
  }
}

Cuándo usar cada herramienta

HerramientaCuándo usarla
MediaQuery.sizeOf(context)Breakpoints globales de la app (móvil/tablet/desktop)
LayoutBuilderAdaptar un widget al espacio que le da su padre
OrientationBuilderCambiar layout al rotar el dispositivo
AspectRatioMantener proporción fija independientemente del tamaño
FractionallySizedBoxDimensiones en porcentaje del padre
Flexible / ExpandedDistribuir espacio en Row/Column

Errores frecuentes

  • MediaQuery.of(context).size en lugar de MediaQuery.sizeOf: la versión antigua reconstruye el widget ante cualquier cambio de MediaQuery (rotación, teclado, status bar), no solo al cambiar el tamaño. Usa sizeOf desde Flutter 3.10+.
  • Breakpoints hardcodeados en múltiples sitios: centraliza los breakpoints en una clase o constantes para mantener consistencia.
  • No probar en tablet con Flutter DevTools: el emulador de escritorio web es la forma más rápida de probar múltiples tamaños. Activa el modo responsive con Ctrl+Shift+M en Chrome.

Aplicación práctica

El diseño responsive es obligatorio si tu app tiene como objetivo Play Store + iPad (App Store) + web. Un mismo código Flutter puede adaptarse a todos si usas LayoutBuilder y breakpoints desde el principio.

Siguiente ejercicio recomendado

Práctica guiada y siguiente paso

FAQ

¿Flutter tiene un AdaptiveScaffold oficial?

Sí. El paquete flutter_adaptive_scaffold (del equipo de Flutter) proporciona un AdaptiveScaffold que automáticamente usa BottomNavigationBar en móvil, NavigationRail en tablet y NavigationDrawer en escritorio. Es una buena base para no reinventar la rueda.

¿Debo usar MediaQuery o LayoutBuilder para hacer un grid adaptativo?

LayoutBuilder. Un grid adaptativo depende del espacio que le da su widget padre, no del tamaño de pantalla completo. LayoutBuilder te da el BoxConstraints exacto disponible.

¿Flutter Web requiere más trabajo de responsive que móvil?

Sí, el rango de tamaños es más amplio (320 dp a 4K) y los usuarios redimensionan ventanas. Planifica desde el principio con LayoutBuilder y mínimos/máximos de anchura para contenedores de contenido.