Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Flutter image automatic slideshow/carousel with random intervals given

I seen there is an image carousel package for flutter.

Widget Carousel = new Container(
child: new Carousel(
  children: [
    new AssetImage('images/img1.jpg'),
    new AssetImage('images/img2.jpg'),
    new AssetImage('images/img3.jpg'),
  ].map((bgImg) => new Image(image: bgImg, width: 1500.0, height: 1500.0, fit: BoxFit.cover)).toList(),
  displayDuration: const Duration(seconds: 1),
),

);

I wanted to know if there is any chance to make this automatic and with random intervals given in an array.

Thank you.

Tried this - is this not consuming too much?

Widget build(BuildContext context) {

SystemChrome.setEnabledSystemUIOverlays([]);

setNewImage() {
  List<int> duration = [5, 7, 3, 10];
  List<String> imageURLs = ["assets/logo.jpg", "assets/logo.png", "assets/side-logo.png", "assets/background.jpg"];

  (i == 4) ? i = 0 : i = i;

  int waitTime = duration[i];
  print("wait time: " + waitTime.toString() + " i: " + i.toString());

  Future.delayed(Duration(seconds: waitTime), () {

    setState(() {
      i++;
      int nextImg = (i+1 == 5) ? 0 : i;
      print("Setting: " + nextImg.toString());
      currentMainImage = imageURLs[nextImg];
    });
  });
}

setNewImageFunction() async {
  await setNewImage();
}

setNewImageFunction();

}

ignore the if statements and the list building... just to image change itself.

like image 365
OrrGorenn Avatar asked Nov 16 '22 21:11

OrrGorenn


1 Answers

Which Flutter plugin are you using? Using carousel_slider, you should be able to configure when the carousel switches to the next page using CarouselController.

CarouselController _carouselController = CarouselController();

...

CarouselSlider(
  items: imageList,
  carouselController: _carouselController,
  options: CarouselOptions(
    autoPlay: false,
  ),
),

Then run a Future<void> that updates the interval for switching Carousel pages.

Future<void>randomizePageInterval(){
  var n = 0;
  var maxDelay = 5;
  while(n == itemList.length){
    /// Generate random interval
    Future.delayed(Duration(seconds: Random().nextInt(maxDelay)), () {
      /// Go to next page
      _carouselController.nextPage(duration: Duration(milliseconds: 300), 
        curve: Curves.linear);
    });
    
    n++;
  }
}
like image 61
Omatt Avatar answered Dec 11 '22 01:12

Omatt