Flutter 用PageView实现轮播

发布时间 2023-12-19 16:18:36作者: angelwgh
import 'package:flutter/material.dart';

class PageSwiper extends StatefulWidget {
  const PageSwiper({super.key});

  @override
  State<PageSwiper> createState() => _PageSwiperState();
}

class _PageSwiperState extends State<PageSwiper> {
  List<Color> colorList = [
    Colors.cyan,
    Colors.pink,
    Colors.indigo,
  ];
  int _index = 0;
  @override
  Widget build(BuildContext context) {
    return Column(
      children: [
        Container(
          width: double.infinity,
          height: 200,
          color: Colors.white,
          child: PageView.builder(
            onPageChanged: (index) {
              setState(() {
                _index = index % 3;
              });
            },
            itemBuilder: (context, index) {
              return Container(
                color: colorList[index % 3],
                child: Center(
                  child: Text(
                    (index % 3 + 1).toString(),
                    style: const TextStyle(
                      color: Colors.white,
                      decoration: TextDecoration.none,
                    ),
                  ),
                ),
              );
            },
          ),
        ),
        Material(
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: List.generate(3, (index) {
              return Container(
                width: 10,
                height: 10,
                margin: EdgeInsets.all(5),
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(5),
                  color: index == _index ? Colors.black54 : Colors.black26,
                ),
              );
            }),
          ),
        )
      ],
    );
  }
}