Home > Software design >  ListView inside SingleChildScrollView: RenderBox was not laid out
ListView inside SingleChildScrollView: RenderBox was not laid out

Time:11-11

I want to have a horizontally scrollable container and inside it somewhere a ListView, which scrolls vertically:

return SingleChildScrollView(
  scrollDirection: Axis.horizontal,
  child: ListView.builder(
    shrinkWrap: true,
    primary: false,
    itemCount: 5,
    itemBuilder: (context, index) {
      return const SizedBox(
        height: 10,
        width: 10,
      );
    },
  ),
);

but I get this error: RenderBox was not laid out. I already put Expanded around everything imaginable. It has to be a SingleChildScrollView.

I need help.

CodePudding user response:

Provide width on ListView, it will solve the issue.

LayoutBuilder( /// needed to be top level
  builder: (context, constraints) => SingleChildScrollView(
    scrollDirection: Axis.horizontal,
    child: SizedBox(
      width: constraints.maxWidth,
      child: ListView.builder(
        primary: false,
        physics: ClampingScrollPhysics(),
        itemCount: 5,
        itemBuilder: (context, index) {
          return const SizedBox(
            height: 10,
            width: 10,
          );
        },
      ),
    ),
  ),
);
SingleChildScrollView(
  scrollDirection: Axis.horizontal,
  child: SizedBox(
    width: MediaQuery.of(context).size.width, //you may get different way like LayoutBuilder on top level
    child: ListView.builder(
      primary: false,
      physics: ClampingScrollPhysics(),
      itemCount: 5,
      itemBuilder: (context, index) {
        return const SizedBox(
          height: 10,
          width: 10,
        );
      },
    ),
  ),
);
  • Related