long25vn / flutter-co-ban

Tuyển tập tài liệu, hướng dẫn, ví dụ về Flutter
5 stars 0 forks source link

The problem when the ListView inside a Column/Row #3

Open long25vn opened 4 years ago

long25vn commented 4 years ago
Container(
          child: ListView(
            children: <Widget>[
              Container(
                height: 300,
                color: Colors.red,
                child: Text("dat"),
              )
            ],
          ),
        )
════════ Exception caught by rendering library ═════════════════════════════════
RenderBox was not laid out: RenderViewport#01d7d NEEDS-LAYOUT NEEDS-PAINT NEEDS-COMPOSITING-BITS-UPDATE
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1687 pos 12: 'hasSize'
long25vn commented 4 years ago

https://stackoverflow.com/a/52801899

The problem is that you are placing the ListView inside a Column/Row. The text in the exception gives a good explanation of the error.

To avoid the error you need to provide a size to the ListView inside.

I propose you this code that uses an Expanded to inform the horizontal size (maximum available) and the SizedBox (Could be a Container) for the height:

        new Row(
          children: <Widget>[
            Expanded(
              child: SizedBox(
                height: 200.0,
                child: new ListView.builder(
                  scrollDirection: Axis.horizontal,
                  itemCount: products.length,
                  itemBuilder: (BuildContext ctxt, int index) {
                    return new Text(products[index]);
                  },
                ),
              ),
            ),
            new IconButton(
              icon: Icon(Icons.remove_circle),
              onPressed: () {},
            ),
          ],
          mainAxisAlignment: MainAxisAlignment.spaceBetween,
        )