flutter_carousel_slider icon indicating copy to clipboard operation
flutter_carousel_slider copied to clipboard

Responsive height

Open erperejildo opened this issue 5 years ago • 29 comments

How can I get a dynamic height for each carousel element?

erperejildo avatar Feb 19 '20 16:02 erperejildo

What I did was create a formula that's based on the device height. You can do this using linear regression.

jacksonw765 avatar Mar 22 '20 15:03 jacksonw765

yeah, I could do that but I was wondering if it was possible using the package itself

erperejildo avatar Mar 24 '20 08:03 erperejildo

Hi, sorry for the late response.

Currently there is no way to define a dynamic height for each carousel item. But I think it can be done by creating a dynamic height container in the carousel item.

serenader2014 avatar Apr 13 '20 12:04 serenader2014

What I did was create a formula that's based on the device height. You can do this using linear regression.

Hi, do you think there is a similar solution for my case? I would like to adapt the the height according to the content and not necessarily based on the device height.

ovib98 avatar Apr 14 '20 20:04 ovib98

Hi, sorry for the late response.

Currently there is no way to define a dynamic height for each carousel item. But I think it can be done by creating a dynamic height container in the carousel item.

I tried that but it didn't work. Do you have any specific idea on mind?

erperejildo avatar Apr 23 '20 09:04 erperejildo

Do you guys think that this feature will be available here soon? I'm also facing this issue, but instead trying a workaround, I'd like a more definitive solution...

Thank you in advance!

finxster avatar May 07 '20 13:05 finxster

Unfortunately, I think it is not easy to implement this feature. Because we use PageView to display the carousel, but PageView doesn't allow us to have a responsive children's height, that being said, you can only create a fixed height carousel item for all the slider :(

serenader2014 avatar May 07 '20 16:05 serenader2014

Thanks @serenader2014. I'll try an alternative workaround then.

finxster avatar May 07 '20 17:05 finxster

Does anybody has an example how to do it / calculate it?

marcel-happyfloat avatar May 15 '20 22:05 marcel-happyfloat

I moved to this hacky solution now I found elsewhere instead of carousel:

                            Column(
                                mainAxisSize: MainAxisSize.min,
                                children: <Widget>[
                                  SingleChildScrollView(
                                    scrollDirection: Axis.horizontal,
                                    child: Row(
                                      mainAxisAlignment: MainAxisAlignment.start,
                                      crossAxisAlignment: CrossAxisAlignment.start,
                                      children: []
                                    ),
                                  ),
                                ],
                              ),

But now my main problem is, that it does not snap to my items in the row... maybe I need a custom scroll handler to fix this.

Edit: Hm, that doesn't solve the problem of the parent scrollview height. I think I will stick with the fixed height carousel for now and just design my App differently.

marcel-happyfloat avatar May 15 '20 22:05 marcel-happyfloat

@serenader2014 A recent package has extended the PageView to be expandable in height (https://pub.dev/packages/expandable_page_view/) Any chance, that this would be integrated in a future version of carousel_slider? Adaptive height is the only thing missing on this otherwise amazing package 🥇

amoscalamida avatar Feb 24 '21 23:02 amoscalamida

Maybe try with dynamic changing height in StatefulWidget. The example below is for changing the width. Sorry for formatting:

`import 'package:carousel_slider/carousel_slider.dart';

class HomeBannerDesktop extends StatefulWidget { const HomeBannerDesktop({Key key}) : super(key: key);

@override _HomeBannerDesktopState createState() => _HomeBannerDesktopState(); }

class _HomeBannerDesktopState extends State<HomeBannerDesktop> { double _width = 370; int _current = 0; static const double _fontSize = 60;

List widths = [370, 700, 600]; List<Widget> textSliders = [ SliderItem( text: "text text.", width: 370, ), SliderItem( text: "text text text text.", width: 700, ), SliderItem( text: "text text text.", width: 600, ), ];

@override Widget build(BuildContext context) { final size = MediaQuery.of(context).size;

return Container(
  width: size.width,
  color: Colors.amber,
  padding: EdgeInsets.only(
    top: 80,
    bottom: 40,
  ),
  child: Center(
    child: Column(
      mainAxisSize: MainAxisSize.min,
      mainAxisAlignment: MainAxisAlignment.center,
      children: [
        Padding(
          child: Container(
            width: 1050,
            child: Row(
              mainAxisSize: MainAxisSize.min,
              mainAxisAlignment: MainAxisAlignment.center,
              children: [
                Container(
                  padding: EdgeInsets.only(
                    right: 20,
                  ),
                  child: Text(
                    "Text:",
                   
                  ),
                ),
                 AnimatedContainer(
                  duration: Duration(
                    milliseconds: 1000,
                  ),
                  child: Container(
                    width: widths[_current],
                    child: Column(
                      children: [
                        CarouselSlider(
                          items: textSliders,
                          options: CarouselOptions(
                              autoPlay: true,
                              autoPlayInterval: const Duration(seconds: 2),
                              autoPlayAnimationDuration: Duration(
                                milliseconds: 800,
                              ),
                              viewportFraction: 1,
                              height: 80,
                              scrollDirection: Axis.vertical,
                              scrollPhysics: ScrollPhysics(),
                              onPageChanged: (index, reason) {
                                setState(() {
                                  _current = index;
                                });
                              }),
                        ),

              ],
            ),
          ),
        ),
      ],
    ),
  ),
);

} }

class SliderItem extends StatelessWidget { final String text; final double width;

const SliderItem({this.text, this.width});

@override Widget build(BuildContext context) { return Center( child: Container( width: width, child: Text( text, textAlign: TextAlign.left, style: TextStyle( ), ), ), ); } } `

PawelZaw avatar Mar 19 '21 16:03 PawelZaw

Any updates on this? I've already implemented a dynamic height on a StatefulWidget using the height property of CarouselOptions, but this is only useful when you know the exactly height of all items (or when you can calculate those heights).

It would be awesome to have the height adapt itself to match item content for variable amounts of text for example.

Leviosar avatar May 18 '21 02:05 Leviosar

I have given solution to this on a stackoverflow question.

Link to answer

Let me know if this solves your issue @Leviosar

shatanikmahanty avatar May 26 '21 07:05 shatanikmahanty

Something that seemed to work for me: Wrap CarouselSlider in Expanded and set aspectRatio to 1/MediaQuery.of(context).devicePixelRatio

purtellap avatar Aug 12 '21 04:08 purtellap

I have been having this same issue with a text only carousel and I managed to solve it by using a text painter to work out the height required max height of the carousel (with help from this stack overflow thread https://stackoverflow.com/questions/52659759/how-can-i-get-the-size-of-the-text-widget-in-flutter)

double getMaxTextWidgetSize(List<String> texts, double textWidth) {
    double height = 10;
    for (var text in texts) {
      final TextPainter textPainter = TextPainter(
          text: TextSpan(
              text: text,
              style: TextStyle(
                  fontSize: 16.0,
                  fontWeight: FontWeight.w500,
                  color: Colors.black87)),
          maxLines: 1,
          textScaleFactor: MediaQuery.of(context).textScaleFactor,
          textDirection: TextDirection.ltr)
        ..layout(minWidth: 0, maxWidth: double.infinity);
      if (textPainter.size.height > height) {
        final countLines = (textPainter.size.width / textWidth).ceil();
        height = countLines * textPainter.size.height;
      }

    }
    return height;
  }

For textWidth, I just approximated the size ratio of my carousel against the total width of the screen and passed that in, which seemed to work fine.

double carouselWidthAsFractionOfScreen = 0.66;
getMaxTextWidgetSize(alternatives, MediaQuery.of(context).size.width* carouselWidthAsFractionOfScreen),

Mijawel avatar Nov 29 '21 01:11 Mijawel

This function would be very helpful.

ArkasDev avatar Jul 11 '22 17:07 ArkasDev

I think this is one of most requested feature

hsul4n avatar Sep 25 '22 13:09 hsul4n

So any solution?

sawirricardo avatar Oct 13 '22 08:10 sawirricardo

So any solution?

almost 3 years now. I don't think we are going to have any

erperejildo avatar Oct 20 '22 09:10 erperejildo

My solution is to use GlobalKey() for each index and get the height. height: _keys[_currentIndex].currentContext?.findRenderObject() as RenderBox?)?.size.height ?? 0

gustavomaedo avatar Nov 29 '22 17:11 gustavomaedo

i need custom width for every one of my items.but viewport fraction does not let me to have it.is there a way? https://github.com/serenader2014/flutter_carousel_slider/issues/397

mahdiqdi avatar Mar 01 '23 15:03 mahdiqdi

i need custom width for every one of my items.but viewport fraction does not let me to have it.is there a way? https://github.com/serenader2014/flutter_carousel_slider/issues/397

Same problem with me , not sure if there is any solution / workaround available for this ?

jay-b-thakkar avatar Jun 19 '23 17:06 jay-b-thakkar

I tried to update the package to use ExpandablePageView and removed some fields and now it works without specifying a height https://github.com/ahmet-fennel/flutter_carousel_slider

ahmet-fennel avatar Jun 27 '23 14:06 ahmet-fennel

I tried to update the package to use ExpandablePageView and removed some fields and now it works without specifying a height https://github.com/ahmet-fennel/flutter_carousel_slider

@ahmet-fennel I tried your package and it's working fine without height but "Infinite Scroll" Feature is not working anymore. Can you please look into that?

krutarth-vaishnav-ups avatar Mar 19 '24 09:03 krutarth-vaishnav-ups