Search code examples
flutterflutter-layouthorizontal-scrolling

Flutter: Scrolling through widgets list


enter image description here

Is there any way in flutter, to only scroll through a certain number of widgets?

Like in PlayStore, the smaller widgets can be scrolled to the next 3 widgets however hard or fast the screen is scrolled. The same can be seen in the larger widgets, which can be scrolled through only one widget at a time?


Solution

  • You just need to think about the top slider as of PageView with each 3 children wrapped in their own parent block.

    Here's an example:

    class SmallSlider extends StatefulWidget {
      @override
      _SmallSliderState createState() => _SmallSliderState();
    }
    
    class _SmallSliderState extends State<SmallSlider> {
      final PageController controller = PageController(viewportFraction: 0.9);
    
      @override
      Widget build(BuildContext context) {
        return AspectRatio(
          aspectRatio: 3 / 2,
          child: PageView.builder(
            controller: controller,
            itemCount: 5,
            itemBuilder: (context, index) => Row(
              children: <Widget>[
                for (int i = 0; i < 3; i++)
                  Expanded(
                    child: SmallSliderItem(),
                  ),
              ],
            ),
          ),
        );
      }
    }
    
    class SmallSliderItem extends StatelessWidget {
      @override
      Widget build(BuildContext context) {
        return Container(
          margin: EdgeInsets.symmetric(horizontal: 5.0),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            crossAxisAlignment: CrossAxisAlignment.start,
            children: <Widget>[
              AspectRatio(
                aspectRatio: 1.0,
                child: Container(
                  decoration: BoxDecoration(
                    color: Colors.grey,
                    borderRadius: BorderRadius.circular(10.0),
                  ),
                ),
              ),
              SizedBox(height: 5.0),
              Text('Title'),
              SizedBox(height: 5.0),
              Text('99 MB'),
            ],
          ),
        );
      }
    }
    

    After that you just assign a PageController with viewportFraction lower than 1.0 so that it will display the next and previous blocks too.