Efficient use of Widgets in Flutter Container – Tip

By | January 12, 2019

 

I am going to show how to efficiently make use of widgets in Flutter.

This is a simple example of how to work with widgets in Flutter.

Here we will be creating two widgets that looks similar, but let’s see how many hierarchies or levels of widgets are needed to create such a widget.

 
Watch Video Tutorial

 
Let’s start then…

 
We will write a function that returns the widget.

 

 Widget myWidget1() {
    return 
        Padding(
            padding: const EdgeInsets.all(10.0),
            child: Container(
            color: Colors.white,
            width: double.infinity,
            child: Center(
                child: Padding(
                padding: EdgeInsets.all(20.0),
                child: Text("Widget 1"),
                ),
            ),
            ),
        );
}

 

The Above widget will look like this in the UI.

Widget 1

Widget 1

 

Now we will create the same widget with the same look and feel with less hierarchies, that means less number of widgets.

I will write another function for that.

 

Widget myWidget2(){
    return Container(
        margin: EdgeInsets.all(10.0),
        padding: EdgeInsets.all(20.0),
        color: Colors.white,
        alignment: Alignment.center,
        child: Text("Widget 2"),
    );
}

 

Now if you add the second widget also to the UI, both will have the same appearance, but with less widgets for second one.

 

 Widget 1 & Widget 2

Widget 1 & Widget 2

 

So thats the power of Container. I believe this will be a good information when you code in Flutter.

Make sure to subscribe to my youtube channel for more Video Tutorials.

Here is one of my Tutorials link.

Please leave your valuable comments below so that it will be an encouragement for me to write more articles and videos.

Leave a Reply

Your email address will not be published. Required fields are marked *