Flutter

How to implement slideshow effect through PageView in Flutter

To achieve a picture slideshow effect, you can use the PageView component combined with a timer to rotate pictures. The following is a sample code that demonstrates how to implement a picture slideshow effect:

import 'dart:async';
import 'package:flutter/material.dart';

class Slideshow extends StatefulWidget {
  final List<String> imageUrls;
  final Duration duration;

  Slideshow({required this.imageUrls, required this.duration});

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

class _SlideshowState extends State<Slideshow> {
  final PageController _pageController = PageController();
  late Timer _timer;
  int _currentPage = 0;

  @override
  void initState() {
    super.initState();
    _timer = Timer.periodic(widget.duration, (_) {
      if (_currentPage < widget.imageUrls.length - 1) {
        _currentPage++;
      } else {
        _currentPage = 0;
      }
      _pageController.animateToPage(
        _currentPage,
        duration: Duration(milliseconds: 500),
        curve: Curves.easeInOut,
      );
    });
  }

  @override
  void dispose() {
    _timer.cancel();
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return PageView.builder(
      controller: _pageController,
      itemCount: widget.imageUrls.length,
      itemBuilder: (BuildContext context, int index) {
        return Image.network(
          widget.imageUrls[index],
          fit: BoxFit.cover,
        );
      },
      onPageChanged: (int index) {
        setState(() {
          _currentPage = index;
        });
      },
    );
  }
}
Slideshow(
  imageUrls: [
    'https://example.com/image1.jpg',
    'https://example.com/image2.jpg',
    'https://example.com/image3.jpg',
  ],
  duration: Duration(seconds: 3),
)

In this example, the Slideshow component receives a list of imageUrls, which contains the image URLs to be rotated. The duration parameter is used to set the time for each picture to stay. PageView.builder is used to display pictures and update the currently displayed pictures according to the timer.

If you need to manually switch pictures by sliding the screen, you can use the PageView component combined with gesture detection to achieve. The following is a sample code that demonstrates how to manually switch images by swiping the screen:

import 'package:flutter/material.dart';

class ImageSlider extends StatefulWidget {
  final List<String> imageUrls;

  ImageSlider({required this.imageUrls});

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

class _ImageSliderState extends State<ImageSlider> {
  PageController _pageController = PageController();
  int _currentPage = 0;

  @override
  void dispose() {
    _pageController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return GestureDetector(
      onHorizontalDragEnd: (details) {
        if (details.velocity.pixelsPerSecond.dx > 0) {
          // Swipe right
          if (_currentPage > 0) {
            setState(() {
              _currentPage--;
            });
            _pageController.previousPage(
              duration: Duration(milliseconds: 300),
              curve: Curves.easeInOut,
            );
          }
        } else if (details.velocity.pixelsPerSecond.dx < 0) {
          // Swipe left
          if (_currentPage < widget.imageUrls.length - 1) {
            setState(() {
              _currentPage++;
            });
            _pageController.nextPage(
              duration: Duration(milliseconds: 300),
              curve: Curves.easeInOut,
            );
          }
        }
      },
      child: PageView.builder(
        controller: _pageController,
        itemCount: widget.imageUrls.length,
        itemBuilder: (BuildContext context, int index) {
          return Image.network(
            widget.imageUrls[index],
            fit: BoxFit.cover,
          );
        },
        onPageChanged: (int index) {
          setState(() {
            _currentPage = index;
          });
        },
      ),
    );
  }
}
ImageSlider(
  imageUrls: [
    'https://example.com/image1.jpg',
    'https://example.com/image2.jpg',
    'https://example.com/image3.jpg',
  ],
)

In this example, the ImageSlider component receives a list of imageUrls, which contains the image URLs to display. Monitor the end event of the horizontal drag gesture through GestureDetector, and switch the currently displayed picture according to the speed and direction of the gesture. PageView.builder is used to display pictures and update the currently displayed pictures according to gesture operations.

Leave a Reply

Your email address will not be published. Required fields are marked *