需要添加依赖 get: 4.6.5
import 'package:flutter/material.dart';
import 'package:get/get.dart';
class VDPageControl extends StatefulWidget {
const VDPageControl({
required this.pageController,
required this.width,
required this.height,
required this.numberOfPages,
this.currentPage = 0,
this.defaultColor = Colors.grey,
this.currentColor = Colors.white,
this.space = 5,
this.dotWidth = 5,
this.dotHeight = 5,
this.currentDotWidth = 10,
this.currentDotHeight = 5,
this.dotRadius = 2,
super.key,
});
final PageController pageController;
final int numberOfPages;
final int currentPage;
final Color defaultColor;
final Color currentColor;
final double space;
final double width;
final double height;
final double dotWidth;
final double dotHeight;
final double currentDotWidth;
final double currentDotHeight;
final double dotRadius;
@override
State createState() {
return _PageControlState();
}
}
class _PageControlState extends State<VDPageControl> {
final RxInt rxPage = 0.obs;
@override
void initState() {
super.initState();
rxPage(widget.currentPage);
widget.pageController.addListener(onPageControllerNotify);
}
@override
void dispose() {
widget.pageController.removeListener(onPageControllerNotify);
super.dispose();
}
void onPageControllerNotify() {
rxPage(widget.pageController.page?.round() ?? 0);
}
BoxDecoration get currentDecoration => BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(widget.dotRadius)),
color: widget.currentColor,
);
BoxDecoration get defaultDecoration => BoxDecoration(
color: widget.defaultColor,
borderRadius: BorderRadius.all(Radius.circular(widget.dotRadius)),
);
@override
Widget build(BuildContext context) {
return Container(
width: widget.width,
height: widget.height,
alignment: Alignment.center,
color: Colors.transparent,
child: SingleChildScrollView(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: List<Widget>.generate(widget.numberOfPages, cell),
),
),
);
}
Widget cell(int index) {
return Obx(() => Center(
child: Container(
margin: EdgeInsets.fromLTRB(0, 0, widget.space, 0),
width: index == rxPage.value ? widget.currentDotWidth : widget.dotWidth,
height: index == rxPage.value ? widget.currentDotHeight : widget.dotHeight,
decoration: index == rxPage.value ? currentDecoration : defaultDecoration,
),
));
}
}