import 'package:flutter/material.dart';
int _getRealIndex(int index, int length) {
return index >= length ? index % length : index;
}
class InfinitySlider extends StatefulWidget {
final int initialPage;
final List<Widget> items;
final double height;
final PageController pageController;
InfinitySlider({
Key? key,
required this.items,
this.height = 10,
this.initialPage = 0,
}) : pageController =
PageController(initialPage: items.length + initialPage),
assert(items.isNotEmpty),
super(key: key);
@override
State<InfinitySlider> createState() => _InfinitySliderState();
}
class _InfinitySliderState extends State<InfinitySlider> {
int length = 0;
@override
void initState() {
// TODO: implement initState
super.initState();
setState(() {
length = widget.items.length;
});
widget.pageController.addListener(pageListener);
}
void pageListener() {
double mediaWidth = MediaQuery.of(context).size.width;
double page = widget.pageController.page as double;
if (page == 0 || page >= (length * 2)) {
double pixels = mediaWidth * (length + page % length);
widget.pageController.position.setPixels(pixels);
}
}
@override
Widget build(BuildContext context) {
return Column(
children: [
SizedBox(
height: widget.height,
child: PageView.builder(
itemBuilder: (BuildContext context, int i) {
final int index = _getRealIndex(i, length);
return widget.items[index];
},
controller: widget.pageController,
),
),
],
);
}
}
标签:index,PageView,pageController,轮播,自定义,int,items,widget,length
From: https://www.cnblogs.com/angelwgh/p/17916921.html