Search code examples
flutterflutter-layout

ListView inside SingleChildScrollView: RenderBox was not laid out


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.


Solution

  • 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,
            );
          },
        ),
      ),
    );