How to use Stack Widget flutter?
By Abhishek on September 7, 2019
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, child: Center( child: Text( 'Green', style: TextStyle(color: Colors.white, fontSize: 20), ), ), ), Container( width: 250, height: 150, color: Colors.red, child: Center( child: Text( 'Red', style: TextStyle(color: Colors.white, fontSize: 20), ), ), ), Container( width: 100, height: 100, color: Colors.indigo, child: Center( child: Text( 'Indigo', style: TextStyle(color: Colors.white, fontSize: 20), ), ), ), ], ...
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.
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.)