Menu
CoddyTech

A Maximum Width

Part of the Layout That Fits section of Coddy's Flutter journey. Lesson 15 of 30.

A card with a long text grows as wide as the screen. On a phone that looks fine; on a tablet the same card stretches into one line a thousand pixels long, which is hard to read.

ConstrainedBox sets limits on the size of its child. maxWidth: is the most it may grow:

ConstrainedBox(
  constraints: const BoxConstraints(maxWidth: 400),
  child: Container(...),
)

On a screen narrower than 400 pixels the card still shrinks to fit. On a wider one it stops at 400, and the text wraps onto more lines.

BoxConstraints also takes minWidth:, minHeight: and maxHeight:. A minimum is the least a child may be, so it never stops one from growing.

challenge icon

Challenge

Easy

Keep the quote card readable on wide screens: let it grow to at most 320 pixels wide.

Try it yourself

import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      home: Scaffold(
        appBar: AppBar(title: const Text('Quote of the Day')),
        body: Padding(
          padding: const EdgeInsets.all(16),
          child: Center(
            child: Container(
              padding: const EdgeInsets.all(24),
              decoration: BoxDecoration(
                color: Colors.amber.shade100,
                borderRadius: BorderRadius.circular(16),
              ),
              child: const Text(
                'The best way to learn to build apps is to build apps, one small screen at a time.',
                style: TextStyle(fontSize: 20),
              ),
            ),
          ),
        ),
      ),
    );
  }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Layout That Fits

Practice on your own: Online Flutter compiler