PageView组件实现翻页和自定义轮播图

发布时间:2023年12月18日

PageView实现上下翻页

?

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_demo/tools/pageViewKeepAlive.dart';

void main() {
  //设置状态栏颜色
  SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.blue, //状态栏背景颜色
      statusBarIconBrightness: Brightness.light //状态栏字体颜色
      ));

  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      //隐藏DEBUG图标
      debugShowCheckedModeBanner: false,
      theme: ThemeData(primarySwatch: Colors.blue),
      home: Scaffold(
        body: PageView.builder(
          //设置PageView纵向滑动
          scrollDirection: Axis.vertical,
          itemCount: 10,
          itemBuilder: (context, index) {
            //使用缓存,注意:页面比较多时缓存会耗费内存
            return PageViewKeepAlive(
              child: PageViewPage(num: index),
            );
          },
        ),
      ),
    );
  }
}

class PageViewPage extends StatefulWidget {
  final int num;

  const PageViewPage({super.key, required this.num});

  @override
  State<PageViewPage> createState() => _PageViewPageState();
}

class _PageViewPageState extends State<PageViewPage> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //SafeArea安全区域组件,状态栏不设置内容
      body: SafeArea(
        child: Center(
          child: Text(
            "第${widget.num + 1}屏",
            style: const TextStyle(fontSize: 50),
          ),
        ),
      ),
    );
  }
}

scrollDirection属性设置PageView上下滑动还是左右滑动,默认左右滑动,Axis.vertical为上下滑动。

PageViewKeepAlive为自定义缓存组件,设置缓存时,第一次加载页面,第二次直接使用缓存页面,使用缓存时会消耗一定内存。

自定义pageViewKeepAlive.dart页面代码:

import 'package:flutter/material.dart';

class PageViewKeepAlive extends StatefulWidget {
  final Widget? child;
  final bool keepAlive;
  const PageViewKeepAlive(
      {Key? key, @required this.child, this.keepAlive = true})
      : super(key: key);

  @override
  State<PageViewKeepAlive> createState() => _PageViewKeepAliveState();
}

class _PageViewKeepAliveState extends State<PageViewKeepAlive> with AutomaticKeepAliveClientMixin{
  @override
  Widget build(BuildContext context) {
    super.build(context);
    return widget.child!;
  }

  @override
  bool get wantKeepAlive => widget.keepAlive;
}

PageView实现自定义轮播图

?

import 'dart:async';

import 'package:flutter/material.dart';

/// 自定义轮播图控件
class Swiper extends StatefulWidget {
  final double width;
  final double height;
  final List<String> list;

  const Swiper({
    super.key,
    this.width = double.infinity,
    this.height = 200,
    required this.list,
  });

  @override
  State<Swiper> createState() => _SwiperState();
}

class _SwiperState extends State<Swiper> {
  int _currentIndex = 0;
  List<Widget> pageList = [];
  late PageController _pageController;
  late Timer timer;

  @override
  void initState() {
    super.initState();
    //数据
    for (var i = 0; i < widget.list.length; i++) {
      pageList.add(
        ImagePage(
          width: widget.width,
          height: widget.height,
          src: widget.list[i],
        ),
      );
    }
    //PageController
    _pageController = PageController(initialPage: 0);
    //定时器
    timer = Timer.periodic(const Duration(seconds: 3), (t) {
      _pageController.animateToPage(
        (_currentIndex + 1) % pageList.length,
        duration: const Duration(microseconds: 200),
        curve: Curves.linear,
      );
    });
  }

  @override
  void dispose() {
    super.dispose();
    //销毁定时器
    timer.cancel();
    _pageController.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        SizedBox(
          height: 200,
          child: PageView.builder(
            controller: _pageController,
            onPageChanged: (index) {
              setState(() {
                _currentIndex = index % pageList.length;
              });
            },
            itemCount: 1000,
            itemBuilder: (context, index) {
              return pageList[index % pageList.length];
            },
          ),
        ),
        //轮播指示器
        Positioned(
          left: 0,
          right: 0,
          bottom: 2,
          child: Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: List.generate(pageList.length, (index) {
              return Container(
                margin: const EdgeInsets.all(5),
                width: 10,
                height: 10,
                decoration: BoxDecoration(
                  color: _currentIndex == index ? Colors.blue : Colors.grey,
                  shape: BoxShape.circle, //圆
                ),
              );
            }).toList(),
          ),
        )
      ],
    );
  }
}

//轮播图片类
class ImagePage extends StatelessWidget {
  final double width;
  final double height;
  final String src;

  const ImagePage({
    super.key,
    this.width = double.infinity,
    this.height = 200,
    required this.src,
  });

  @override
  Widget build(BuildContext context) {
    return SizedBox(
      width: double.infinity,
      height: 200,
      child: Image.network(
        src,
        fit: BoxFit.cover,
      ),
    );
  }
}

用到的组件有Timer定时器,设置图片自动轮播,Duration设置轮播图停留的持续时间。Positioned轮播图小圆点指示器组件。

主页面引用自定义轮播控件:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_demo/widget/swiper.dart';

void main() {
  //设置状态栏颜色
  SystemChrome.setSystemUIOverlayStyle(const SystemUiOverlayStyle(
      statusBarColor: Colors.blue, //状态栏背景颜色
      statusBarIconBrightness: Brightness.light //状态栏字体颜色
      ));

  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      //隐藏DEBUG图标
      debugShowCheckedModeBanner: false,
      theme: ThemeData(primarySwatch: Colors.blue),
      home: const Scaffold(
        body: PageViewPageSwiper(),
      ),
    );
  }
}

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

  @override
  State<PageViewPageSwiper> createState() => _PageViewSwiperPageState();
}

class _PageViewSwiperPageState extends State<PageViewPageSwiper> {
  List<String> list = [];

  @override
  void initState() {
    super.initState();
    list = const [
      "https://www.itying.com/images/flutter/1.png",
      "https://www.itying.com/images/flutter/2.png",
      "https://www.itying.com/images/flutter/3.png",
    ];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      //SafeArea安全区域组件,状态栏不设置内容
      body: SafeArea(
        child: ListView(
          children: [
            //引用自定义轮播控件
            Swiper(list: list),
          ],
        ),
      ),
    );
  }
}

文章来源:https://blog.csdn.net/juer2017/article/details/135061916
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。