skip to Main Content

My card is taking the whole screen width, while being inside of a SizedBox of width 50 (much smaller than the screen). What’s going on? Here’s my code:

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return ListView(
    children: const [
      SizedBox(
        width: 50,
        child: Card(
        child: Row(
          children: [
          Text('test'),
        ]),
        ),
      ),
    ]
    );
  }
}

2

Answers


  1. You can wrap the child of ListView with UnconstrainedBox Widget.

    From Official Docs: UnconstrainedBox imposes no constraints on its child, allowing it to render at its "natural" size. Link

    class MyWidget extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return ListView(
        children: const [
          UnconstrainedBox(
            child: SizedBox(
              width: 50,
              child: Card(
              child: Row(
                children: [
                Text('test'),
              ]),
              ),
            ),
          ),
        ]
        );
      }
    }
    
    Login or Signup to reply.
  2. The Listview widget completely controls their children width and height, you can solve this issue using UnconstrainedBox widget before your widget

     Scaffold(
              backgroundColor: Colors.teal,
              body: ListView(children: [
                UnconstrainedBox(
                  child: Card(
                    child: SizedBox(
                      width: 100,
                      child: Row(children: [
                        Text('test'),
                      ]),
                    ),
                  ),
                ),
              ])),
    

    there are two more solutions 1- using row 2- use stack before your widget , you can check this link for more information.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search