Flexible Hugs Its Child
Part of the Layout That Fits section of Coddy's Flutter journey. Lesson 3 of 30.
Expanded makes a child fill the space that is left, even when the child needs less. A chat bubble wrapped in Expanded stretches across the whole row for a one word message.
Flexible gives a child the same space at most, and lets it stay smaller:
Row(
children: [
const CircleAvatar(child: Text('A')),
Flexible(
child: Container(
color: Colors.grey.shade300,
child: const Text('Hello'),
),
),
],
)A short message gets a small bubble. A long message grows until it reaches the edge of the row, then wraps onto more lines, because Flexible never lets it take more than the space that is left.
Use Expanded when the child should fill the space, and Flexible when it may fill it.
Challenge
EasyThe Hi! bubble stretches across the whole screen. Make each bubble only as wide as its message, while the long message still wraps inside the screen.
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('Chat')),
body: Padding(
padding: const EdgeInsets.all(16),
child: Column(
children: [
Row(
children: [
const CircleAvatar(child: Text('S')),
const SizedBox(width: 8),
Expanded(
child: Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.grey.shade300,
borderRadius: BorderRadius.circular(16),
),
child: const Text('Hi!'),
),
),
],
),
const SizedBox(height: 12),
Row(
children: [
const CircleAvatar(child: Text('S')),
const SizedBox(width: 8),
Expanded(
child: Container(
padding: const EdgeInsets.all(12),
decoration: BoxDecoration(
color: Colors.grey.shade300,
borderRadius: BorderRadius.circular(16),
),
child: const Text(
'Are you coming to the park later? We meet at the big tree by the lake.',
),
),
),
],
),
],
),
),
),
);
}
}
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 ApartPractice on your own: Online Flutter compiler