How to use Stack Widget flutter?


Flutter - How to use Stack Widget in flutter

If you are wondering, checkout our 2 minute read post What is flutter. Since Everything in flutter is a Widget. It is good to have a basic understanding of what a particular widget does. We will be picking up one widget per weekly to explain about it in brief about it. Keep yourself updated.


What is Stack in flutter?

Stack is another widget provided by flutter that positions its child widgets relative to edge of the example. Doesn’t ring any bell?? We will cover with example.

Stack can have two types of child widgets within them. These are Positioned and Non-positioned widgets.

Postioned - Those which are wrapped within Positioned widget, something like the following:

Positioned(
  child: Container(
    ...
  )
)

Stack takes children as argument, which is list of elements that will be part of the stack. The elements are placed on the screen starting from the first child being at the bottom to the last child at the top and is left to right in alignment.

The following code will draw three containers on the mobile screen, with green, red and indigo colored containers respectively.

...
Stack(
  children: <Widget>[
    Container(
      width: 400,
      height: 400,
      color: Colors.green[300],
      child: Center(
        child: Text(
          'Green',
          style: TextStyle(color: Colors.white, fontSize: 20),
        ),
      ),
    ),
    Container(
      width: 250,
      height: 150,
      color: Colors.red[400],
      child: Center(
        child: Text(
          'Red',
          style: TextStyle(color: Colors.white, fontSize: 20),
        ),
      ),
    ),
    Container(
      width: 100,
      height: 100,
      color: Colors.indigo[300],
      child: Center(
        child: Text(
          'Indigo',
          style: TextStyle(color: Colors.white, fontSize: 20),
        ),
      ),
    ),
  ],
...


App Preview

stack-app-flutter

As you can see in the example, that the Green was provided as the first child so it is bottom most amoung the three containers and Indigo colored container being at the top, and the Red one is in middle.

Using Postioned Widget with Stack widget.



The Positioned widget when used with stack widget allows to position child widget within the space. Let’s see how : How to use Positioned Widget with Stack? (2 min read.)

Recommended Posts

Default Enum in Rails 6
Rails 6 provides a way to define default enum value. Let’s see how it works...
Ruby 2.7 adds Enumerable#tally
After introducing the Enumerable#tally method in Ruby 2.7-preview updates. #tally as the name suggests gives...
How to rename column name in Rails
Rails rename_column Rails provides a simple method rename_column which can be used in a migration....