Search code examples
flutterwidgetscrollviewflutter-pageview

PageView.builder inside SingleChildScrollView flutter


I am trying to use PageView.builder inside SingleChildScrollView but I always get an error that say

RenderBox was not laid out: RenderRepaintBoundary#490ce relayoutBoundary=up15 NEEDS-PAINT
'package:flutter/src/rendering/box.dart':
Failed assertion: line 1694 pos 12: 'hasSize'

here is part of the code

@override
  Widget build(BuildContext context) {
    return SafeArea(
      child: Scaffold(
        body: SingleChildScrollView(
            child: PageView.builder(
          itemCount: 3,
          scrollDirection: Axis.horizontal,
          reverse: false,
          itemBuilder: (BuildContext context, int index) {
            return Padding(
              padding: EdgeInsets.symmetric(horizontal: 4.0),
              child: Container(
                decoration: BoxDecoration(
                  color: Colors.grey,
                  borderRadius: BorderRadius.all(Radius.circular(4.0)),
                ),
              ),
            );
          },
        )
.....

is there something that I should add from the code?


Solution

  • If you want the child of the PageView widget to be scrollable then try to wrap the root widget of the itemBuilder method with the SingleChildScrollView widget and remove it from its current position.

    So the code would be like that:

    @override
      Widget build(BuildContext context) {
        return SafeArea(
          child: Scaffold(
            body: PageView.builder(
              itemCount: 3,
              scrollDirection: Axis.horizontal,
              reverse: false,
              itemBuilder: (BuildContext context, int index) {
                return SingleChildScrollView( // Moving this widget down to this position is the only change in the code...
                  child: Padding(
                    padding: EdgeInsets.symmetric(horizontal: 4.0),
                    child: Container(
                      decoration: BoxDecoration(
                        color: Colors.grey,
                        borderRadius: BorderRadius.all(Radius.circular(4.0)),
                      ),
                    ),
                  ),
                );
              },
            ),
    .....
    

    The problem is that the SingleChildScrollView widget takes an infinite height because the scrolling functionality and the PageView widget tries to take all the available height so it's trying to take an infinite height and I think this is what causing the problem.