Search code examples
flutternestedflutter-layoutflutter-dependenciesflutter-web

Flutter: How to copy and paste same style on widgets? (to apply same properties repeatedly on children)


1. Background

I want to apply same style on several widgets. First, I tried 'wrapping'. I wrapped all widgets or children that needs same style to one container or raw/column, but this didn't allow me to control specific styles on specific child.

2. Example

Suppose that I want to make three icons on the app bar with same padding. Here is my example code.

1) using row wrap

actions: [
        Padding(
          padding: const EdgeInsets.fromLTRB(0,0,200,0),
          child: Row(
            children: const [
              Icon(Icons.search),
              Icon(Icons.menu),
              Icon(Icons.notifications)
            ],
          ),
        ),
      ],

I expected three icons may separate with right-padding(200), but the entire row was moved with right-padding(200), without having changes on padding of each icons.

2) applying the style one by one

         actions: [
        Row(
          children: const [
            Padding(
              padding: EdgeInsets.fromLTRB(0, 0, 200, 0),
              child: Icon(Icons.search),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(0, 0, 200, 0),
              child: Icon(Icons.menu),
            ),
            Padding(
              padding: EdgeInsets.fromLTRB(0, 0, 200, 0),
              child: Icon(Icons.notifications),
            )
          ],
        ),
      ],

got the result what i want, not the solution that i need

3. Question

I really want to know how to apply same style (or just same padding) to the children, not by controlling every components one by one.

Imagine if the icons were 300, not 3. I may had to control each padding one by one. It might be a padding hell..

The result of the first code The result of the second code


Solution

  • Read about making classes. That's what you need, you just want to do your code shorter. You need to make class called for example button, in there you must to add parameters and invoke this class button whenever you want to use it. Here's good video about it.