123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135 |
- import 'dart:async';
- import 'package:flutter/material.dart';
- /// Description: custom banner
- /// Time : 07/17/2023 Monday
- /// Author : liuyuqi.gov@msn.cn
- class CustomBanner extends StatefulWidget {
- final List<String> _images;
- final double height;
- final ValueChanged<int> onTap;
- final Curve curve;
- const CustomBanner(
- this._images, {
- super.key,
- this.height = 200,
- required this.onTap,
- this.curve = Curves.linear,
- });
- @override
- _CustomBannerState createState() => _CustomBannerState();
- }
- class _CustomBannerState extends State<CustomBanner> {
- late PageController _pageController;
- late int _curIndex;
- late Timer _timer;
- @override
- void initState() {
- super.initState();
- _curIndex = widget._images.length * 5;
- _pageController = PageController(initialPage: _curIndex);
- _initTimer();
- }
- @override
- Widget build(BuildContext context) {
- return Stack(
- alignment: Alignment.bottomCenter,
- children: [
- _buildPageView(),
- _buildIndicator(),
- ],
- );
- }
- Widget _buildIndicator() {
- var length = widget._images.length;
- return Positioned(
- bottom: 10,
- child: Row(
- children: widget._images.map((s) {
- return Padding(
- padding: const EdgeInsets.symmetric(horizontal: 3.0),
- child: ClipOval(
- child: Container(
- width: 8,
- height: 8,
- color: s == widget._images[_curIndex % length]
- ? Colors.white
- : Colors.grey,
- ),
- ),
- );
- }).toList(),
- ),
- );
- }
- Widget _buildPageView() {
- var length = widget._images.length;
- return SizedBox(
- height: widget.height,
- child: PageView.builder(
- controller: _pageController,
- onPageChanged: (index) {
- setState(() {
- _curIndex = index;
- if (index == 0) {
- _curIndex = length;
- _changePage();
- }
- });
- },
- itemBuilder: (context, index) {
- return GestureDetector(
- onPanDown: (details) {
- _cancelTimer();
- },
- onTap: () {
- ScaffoldMessenger.of(context).showSnackBar(
- SnackBar(
- content: Text('当前 page 为 ${index % length}'),
- duration: const Duration(milliseconds: 500),
- ),
- );
- },
- child: Image.asset(
- widget._images[index % length],
- fit: BoxFit.cover,
- ),
- );
- },
- ),
- );
- }
- /// 点击到图片的时候取消定时任务
- _cancelTimer() {
- _timer.cancel();
- _initTimer();
- }
- /// 初始化定时任务
- _initTimer() {
- _timer = Timer.periodic(const Duration(seconds: 3), (t) {
- _curIndex++;
- _pageController.animateToPage(
- _curIndex,
- duration: const Duration(milliseconds: 300),
- curve: Curves.linear,
- );
- });
- }
- /// 切换页面,并刷新小圆点
- _changePage() {
- Timer(const Duration(milliseconds: 350), () {
- _pageController.jumpToPage(_curIndex);
- });
- }
- }
|