How can I stretch a container vertically to max screen?

Viewed 113
body: SafeArea(
      child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
        Container(
          width: 100.00,
          height: 100.00,
          color: Colors.red,
        ),
      ])),
));

Currently, the height is 100.00, but I need to stretch it to infinity.

I tried to change the height to double.infinity:

Container(
          width: 100.00,
          height: double.infinity,
          color: Colors.red,

But then I receive the following error:

The following assertion was thrown during performLayout(): BoxConstraints forces an infinite height.

3 Answers

To achieve this, you can either:

1) Use a widget called Expanded widget.

body: SafeArea(
      child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
       Expanded(
          child: Container(
            color: Colors.red,
          ),
        ),
      ])),
));

2) Give the Container a height and width of the device screen using the MediaQuery class

body: SafeArea(
      child: Column(
          mainAxisAlignment: MainAxisAlignment.start,
          children: <Widget>[
        Container(
          // give it a width equals to the device screen
          width: MediaQuery.of(context).size.width,
          // give it a height equals to the device screen
          height: MediaQuery.of(context).size.height,
          color: Colors.red,
        ),
      ])),
));

Wrap your Container with an Expanded-Widget and remove the height completely.

Expanded(
          child: Container(
            width: 100.00,
            color: Colors.red,
          ),
        ),

The Expanded-Widget fills the available space of the child of a Row or a Column along the main-axis.

The right way to assign height to is the calculating height of

  1. App Bar
  2. Top Bar Space(Exist on the above App Bar)
  3. Remaining screen

Logic:

1. Get the MediaQuer

 final mediaQuery = MediaQuery.of(context);

2. Declare the AppBar Widget and same App Bar instance should be used in Scaffold App Bar

final PreferredSizeWidget appBar = AppBar(
      title: Text('Home'),
    );

3. Use calculated height

      Container(
              width: mediaQuery.size.width,
              height: (mediaQuery.size.height -
                  appBar.preferredSize.height -
                  mediaQuery.padding.top),
              color: Colors.red,
            ),
Related