Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Don't center a PageView - Flutter

Tags:

flutter

dart

I am currently using the carousel-slider library to get a carousel in Flutter.

This library is based on a PageView, and in a PageView the elements are centered.

That's the carousel I get:

First carousel

And this is what I'd like to have:

Wanted carousel

Here is the code where is use the CarouselSlider:

CarouselSlider(
    height: 150,
    viewportFraction: 0.5,
    initialPage: 0,
    enableInfiniteScroll: false,
    items: widget.user.lastGamesPlayed.map((game) {
      return Builder(
        builder: (BuildContext context) {
          return Padding(
              padding: EdgeInsets.symmetric(horizontal: 10),
              child: GestureDetector(
                  onTap: () {
                    game.presentGame(context, widget.user);
                  },
                  child: ClipRRect(
                      borderRadius: BorderRadius.all(Radius.circular(25)),
                      child: Container(
                        color: Theme.MyColors.lightBlue,
                        child: Center(
                          child: Padding(
                              padding: EdgeInsets.all(20),
                              child: AutoSizeText(game.name,
                                  style: TextStyle(fontSize: 70),
                                  maxLines: 1)),
                        ),
                      ))));
        },
      );
    }).toList(),
  )

And here is the code inside the CarouselSlider library:

@override
Widget build(BuildContext context) {
return getWrapper(PageView.builder(
  physics: widget.isScrollEnabled
      ? AlwaysScrollableScrollPhysics()
      : NeverScrollableScrollPhysics(),
  scrollDirection: widget.scrollDirection,
  controller: widget.pageController,
  reverse: widget.reverse,
  itemCount: widget.enableInfiniteScroll ? null : widget.items.length,
  onPageChanged: (int index) {
    int currentPage =
        _getRealIndex(index, widget.realPage, widget.items.length);
    if (widget.onPageChanged != null) {
      widget.onPageChanged(currentPage);
    }
  },
  itemBuilder: (BuildContext context, int i) {
    final int index = _getRealIndex(
        i + widget.initialPage, widget.realPage, widget.items.length);

    return AnimatedBuilder(
      animation: widget.pageController,
      child: widget.items[index],
      builder: (BuildContext context, child) {
        // on the first render, the pageController.page is null,
        // this is a dirty hack
        if (widget.pageController.position.minScrollExtent == null ||
            widget.pageController.position.maxScrollExtent == null) {
          Future.delayed(Duration(microseconds: 1), () {
            setState(() {});
          });
          return Container();
        }
        double value = widget.pageController.page - i;
        value = (1 - (value.abs() * 0.3)).clamp(0.0, 1.0);

        final double height = widget.height ??
            MediaQuery.of(context).size.width * (1 / widget.aspectRatio);
        final double distortionValue = widget.enlargeCenterPage
            ? Curves.easeOut.transform(value)
            : 1.0;

        if (widget.scrollDirection == Axis.horizontal) {
          return Center(
              child:
                  SizedBox(height: distortionValue * height, child: child));
        } else {
          return Center(
              child: SizedBox(
                  width:
                      distortionValue * MediaQuery.of(context).size.width,
                  child: child));
        }
      },
    );
  },
));

}

How can I prevent elements from being centered?

Thank you in advance

like image 642
R3J3CT3D Avatar asked Apr 16 '19 01:04

R3J3CT3D


1 Answers

If you don't want to animate page size over scroll there is no need to use this carousel-slider library.

Also, PageView is not the best Widget to achieve the layout you want, you should use a horizontal ListView with PageScrollPhysics.

import 'package:flutter/material.dart';

class Carousel extends StatelessWidget {
  Carousel({
    Key key,
    @required this.items,
    @required this.builderFunction,
    @required this.height,
    this.dividerIndent = 10,
  }) : super(key: key);

  final List<dynamic> items;
  final double dividerIndent;

  final Function(BuildContext context, dynamic item) builderFunction;

  final double height;

  @override
  Widget build(BuildContext context) {
    return Container(
      height: height,
      child: ListView.separated(
          physics: PageScrollPhysics(),
          separatorBuilder: (context, index) => Divider(
                indent: dividerIndent,
              ),
          scrollDirection: Axis.horizontal,
          itemCount: items.length,
          itemBuilder: (context, index) {
            Widget item = builderFunction(context, items[index]);
            if (index == 0) {
              return Padding(
                child: item,
                padding: EdgeInsets.only(left: dividerIndent),
              );
            } else if (index == items.length - 1) {
              return Padding(
                child: item,
                padding: EdgeInsets.only(right: dividerIndent),
              );
            }
            return item;
          }),
    );
  }
}

Usage

           Carousel(
              height: 150,
              items: widget.user.lastGamesPlayed,
              builderFunction: (context, item) {
                return ClipRRect(
                  borderRadius: BorderRadius.all(Radius.circular(25)),
                  child: Container(
                    width: 200,
                    color: Theme.MyColors.lightBlue,
                    child: Center(
                      child: Padding(
                        padding: EdgeInsets.all(20),
                        child: AutoSizeText(
                          item.name,
                          style: TextStyle(fontSize: 70),
                          maxLines: 1,
                        ),
                      ),
                    ),
                  ),
                );
              },
            )

UPDATE

As observed by @AdamK, my solution doesn't have the same scroll physics behavior as a PageView, it acts more like a horizontal ListView.

If you are looking for this pagination behavior you should consider to write a custom ScrollPhysics and use it on your scrollable widget.

This is a very well explained article that helps us to achieve the desired effect.

like image 90
haroldolivieri Avatar answered Nov 09 '22 16:11

haroldolivieri