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
EasyKeep 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),
),
),
),
),
),
);
}
}
This lesson includes a short quiz. Start the lesson to answer it and track your progress.
All lessons in Layout That Fits
1Sharing a Row
Expanded Fills the RowSharing Space With flexFlexible Hugs Its ChildSpacer Pushes Apart4Sizes and Breakpoints
Full Width: double.infinityA Maximum WidthScreen Size: MediaQueryLayoutBuilder BreakpointsPractice on your own: Online Flutter compiler