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

本文介绍了如何在Flutter中使用PageView实现上下滚动,并展示了如何创建自定义缓存组件PageViewKeepAlive以优化性能。同时,还讲解了如何使用Swiper实现轮播图功能,包括定时器和指示器的使用。
摘要由CSDN通过智能技术生成

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),
          ],
        ),
      ),
    );
  }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

举儿

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值