Spacer Pushes Apart
Part of the Layout That Fits section of Coddy's Flutter journey. Lesson 4 of 30.
A top bar often has a logo on the left and links on the right. A Spacer does that: it is an empty widget that takes all the space left in the row, and pushes everything after it to the other end.
Row(
children: [
const Text('Logo'),
const Spacer(),
const Text('Cart'),
],
)The Spacer goes exactly where the gap should be. Widgets before it stay on the left, widgets after it move to the right, and the space between neighbors on the same side stays as you made it.
mainAxisAlignment: MainAxisAlignment.spaceBetween spreads every child apart instead. Use a Spacer when only one gap should grow.
Challenge
EasyKeep Coddy on the left and push Help and Log in to the right edge, still 16 pixels apart.
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(
body: Padding(
padding: const EdgeInsets.fromLTRB(16, 48, 16, 16),
child: Column(
children: [
Row(
children: [
const Text(
'Coddy',
style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold),
),
const Text('Help'),
const SizedBox(width: 16),
const Text('Log in'),
],
),
],
),
),
),
);
}
}
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