How to Create Full Width Column in Flutter

In this blog post, we’re looking into an essential topic: how to create a full-width column in Flutter. Making your Column widget take up the entire screen width can be crucial for building responsive UIs.

Use CrossAxisAlignment.stretch

What is CrossAxisAlignment.stretch?

CrossAxisAlignment.stretch is a property that can be set on the Column widget. It ensures that the children stretch horizontally to fill the column.

Example Code

Here’s how you can implement it:

Column(
  crossAxisAlignment: CrossAxisAlignment.stretch,
  children: [
    Text('First Child'),
    Text('Second Child'),
  ],
)

Code Explanation

  • Column Widget: We start with a Column widget.
  • CrossAxisAlignment.stretch: The CrossAxisAlignment is set to stretch.
  • Children: Next, we add our child widgets. Here, two Text widgets.
  • Outcome: Each child will now occupy the full width of the column.

Use Container as Parent with MediaQuery

Example Code

An alternative method involves wrapping the Column widget within a Container and setting its width using MediaQuery.

Container(
  width: MediaQuery.of(context).size.width,
  child: Column(
    children: [
      Text('First Child'),
      Text('Second Child'),
    ],
  ),
)

Code Explanation

  • Container: In this method, we start by wrapping the Column inside a Container.
  • MediaQuery: We set the width of the Container using MediaQuery to take the full width of the screen.
  • Column and Children: Inside this Container, we place our Column with its children.

Following is the complete code for reference.

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(
      title: 'Flutter Demo',
      theme: ThemeData(
        colorScheme: ColorScheme.fromSeed(seedColor: Colors.deepPurple),
        useMaterial3: true,
      ),
      home: const MyHomePage(),
    );
  }
}

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

  @override
  Widget build(BuildContext context) {
    return Scaffold(
        appBar: AppBar(
          backgroundColor: Theme.of(context).colorScheme.inversePrimary,
          title: const Text(
            'Flutter Example',
          ),
        ),
        body: Container(
          width: MediaQuery.of(context).size.width,
          child: const Column(
            children: [
              Text('First Child'),
              Text('Second Child'),
            ],
          ),
        ));
  }
}

Making a full-width Column in Flutter is straightforward once you know the methods. You can opt for CrossAxisAlignment.stretch for a simpler approach or use a Container with MediaQuery for more control. Pick what suits your project the best!

Similar Posts

Leave a Reply