skip to Main Content

I am creating custom widget where a container with border and child is IconButton,

here i want to place iconbutton inside container with fixed height and width but its taking main container’s height and width

completly failing to understand how widget works with each other’s size

sometime based on parent size and sometime on its child…is there any good way to understand this topic?

in my following code i want iconbutton of 40×40 in a container of 100×100,

i mean it should be clickable only 40×40

return  Scaffold(

      body:Center(
        child: Container(

          height: 100,
          width: 100,
          decoration: BoxDecoration(
            border: Border.all(color: Colors.black),
          ),

          child: SizedBox(
            height: 40,
            width: 40,
            child: IconButton(onPressed: (){},icon: Icon(Icons.shopping_basket),
            padding: EdgeInsets.zero,
            ),
          ),
        ),
      )
    );

2

Answers


  1. First, IconButton is a Material Design widget which follows the spec that tappable objects need to be at least 48px on each side

    So if you want to understand the constraint, you should change IconButton to another widget, like Container, for example:

    return Scaffold(
          body: Center(
            child: Container(
              height: 100,
              width: 100,
              decoration: BoxDecoration(
                border: Border.all(color: Colors.black),
              ),
              child: Center(
                child: Container(
                  height: 40,
                  width: 40,
                  color: Colors.red,
                ),
              ),
            ),
          ),
        );
    

    The different here is the Center widget, widget in Flutter follow the rule Constraints go down. Sizes go up. Parent sets position.

    You can understand it by this documentation: https://docs.flutter.dev/ui/layout/constraints

    Login or Signup to reply.
  2. You can add some padding to the Sizedbox by making it a container and then this will reduce the clickable area:

    body: Center(
              child: Container(
                height: 100,
                width: 100,
                decoration: BoxDecoration(
                  border: Border.all(color: Colors.black),
                ),
                child: Container(
                  padding: EdgeInsets.all(10),
                  height: 40,
                  width: 40,
                  child: IconButton(
                    onPressed: () {},
                    icon: Icon(Icons.shopping_basket),
                    padding: EdgeInsets.zero,
                  ),
                ),
              ),
            ));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search