SizedBox Widget

What is SizedBox Widget?

The SizedBox is to create a box with a specified size.

Default Constructor

The default constructor which creates a fixed size box.

SizedBox(
  width: // If non-null, requires the child to have exactly this width.
  height: // If non-null, requires the child to have exactly this height.
  child: // child widget
)

Constructor Parameters

It contains many input parameters which can be configured to change its behavior and appearance.

The width and height parameters can be null to indicate that the size of the box should not be constrained in the corresponding dimension.

Code snippet

The following code snippet shows how to use SizedBox widget.

SizedBox(
        width: 200.0,
        height: 30.0,
        child: RaisedButton(
          onPressed: () {},
          child: Text('Create Account'),
        ),
      );

Demo Code

This example makes the RaisedButton have the exact size 200x30.

import 'package:flutter/material.dart';

class SizedBoxDemo extends StatelessWidget {
  Widget build(BuildContext context) {
    return Center(
        child: SizedBox(
      width: 200.0,
      height: 30.0,
      child: RaisedButton(
        onPressed: () {},
        child: Text('Create Account'),
      ),
    ));
  }
}

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(
          title: Text('SizedBox'),
        ),
        body: SizedBoxDemo(),
      ),
    );
  }
}

void main() => runApp(MyApp());

How SizedBox Works?

  1. If given a child, this widget forces its child to have a specific width and/or height (assuming values are permitted by this widget's parent).
  2. If either the width or height is null, this widget will size itself to match the child's size in that dimension.
  3. If not given a child, [SizedBox] will try to size itself as close to the specified height and width as possible given the parent's constraints.
  4. If [height] or [width] is null or unspecified, it will be treated as zero.