Flutter轮播图:Swiper与PageView,及PageView的应用

1.Swiper

常用的一个轮播图组件是Swiper组件,它是第三方的一个组件,需要自行引入才能使用。

基本参数:
Flutter轮播图:Swiper与PageView,及PageView的应用_第1张图片

如果你使用的是 Flutter2.2.0 以及 Flutter2.2.0 之后的版本请使用flutter_swiper_null_safety,
如果您使用的是 Flutter2.2.0 之前的版本请使用 flutter_swiper。

flutter_swiper_null_safety 和 flutter_swiper 用法完全一样

Swiper的简单使用:

Swiper(
          itemBuilder: (BuildContext context, int index) {
            return new Image.network(
              'https://cdn.pixabay.com/photo/2023/03/18/06/53/rose-7860008__340.jpg',
              fit: BoxFit.fill,
            );
          },
          itemCount: 3 //意思是循环遍历几次,然后赋值给Swiper
          ),

Flutter轮播图:Swiper与PageView,及PageView的应用_第2张图片
这个样式通常用于引导页

class _SwiperPageState extends State<SwiperPage> {
  List<Map> imgList=[
    {
      'url':'https://cdn.pixabay.com/photo/2023/03/18/06/53/rose-7860008__340.jpg'
    },
    {
      'url':'https://cdn.pixabay.com/photo/2023/03/20/00/30/anthurium-7863531_640.jpg'
    },
    {
      'url':'https://cdn.pixabay.com/photo/2022/10/08/16/47/austria-7507345__340.jpg'
    },
  ];
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Swiper演示'),
      ),
      body: Column(
        children: [
          Container(
            //width: double.infinity,
            child: AspectRatio(    ///用于配置图片比例
              aspectRatio: 16/9,
              child: Swiper(
                  itemBuilder: (BuildContext context, int index) {
                    return new Image.network(
                      imgList[index]['url'],
                      fit: BoxFit.fill,
                    );
                  },
                  itemCount: imgList.length //意思是循环遍历几次,然后赋值给Swiper
              ),
            )
          ),
          Row(
            children: [

            ],
          )
        ],
      )
    );
  }
}

Flutter轮播图:Swiper与PageView,及PageView的应用_第3张图片

想要了解更多,可以直接看GitHub文档

2.PageView,PageView.builder

pageview是一个滑动页面组件,默认是全屏。
PageView的简单使用:

PageView(
        scrollDirection: Axis.vertical,   //配置滑动方向,默认是水平
        children: [
          Center(
            child: Text('第一屏',style: Theme.of(context).textTheme.headline1,),
          ),
          Center(
            child: Text('第二屏',style: Theme.of(context).textTheme.headline1,),
          ),
        ],
      ),

Flutter轮播图:Swiper与PageView,及PageView的应用_第4张图片
实现了类似短视频的滑动效果

PageView.builder的简单使用:

与ListViewBuilder用法类似

PageView.builder(
        scrollDirection: Axis.vertical,  //垂直滑动
          itemCount: 10,  //循环次数
          itemBuilder: (context,index){
           return  Center(
             child: Text('第${index +1}屏',style: Theme.of(context).textTheme.headline1,),
           );
          }),

使用pageview实现无限下拉加载

import 'package:flutter/material.dart';

class PageViewFullPage extends StatefulWidget {
  const PageViewFullPage({Key? key}) : super(key: key);

  @override
  State<PageViewFullPage> createState() => _PageViewFullPageState();
}

class _PageViewFullPageState extends State<PageViewFullPage> {

  List<Widget> list=[];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    for(var i = 0;i < 10;i++){
      list.add(Center(child: Text('第${i+1}屏',style: TextStyle(fontSize: 60)),));
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('PageViewFull'),),
      body: PageView(
        scrollDirection: Axis.vertical,
        onPageChanged: (index){       //page改变时触发
          if(index+2==list.length){  //当i=8时给list增加数据,从而实现无限下滑
            for(var i = 0;i < 10;i++)
            list.add(Center(child: Text('第${i+1}屏',style: TextStyle(fontSize: 60)),));
          }
        },
        children: list,
      ),
    );
  }
}

使用pageview实现无限轮播效果:

我们将图片处理专门抽离出来:

ImagePage.dart:

import 'package:flutter/material.dart';

class ImagePage extends StatelessWidget {
  final double width;
  final double height;
  final String src;

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

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

PageViewSwiper.dart:

import 'package:flutter/material.dart';
import 'package:untitled7/ImagePage.dart';

class PageViewSwiperPage extends StatefulWidget {
  const PageViewSwiperPage({Key? key}) : super(key: key);

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

class _PageViewSwiperPageState extends State<PageViewSwiperPage> {
  List<Widget> list=[];

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    list=const[
      ImagePage(
        src: 'https://cdn.pixabay.com/photo/2023/03/25/10/00/bee-7875530__340.jpg',
      ),
      ImagePage(
        src: 'https://cdn.pixabay.com/photo/2023/03/27/11/17/wild-plant-7880509__340.jpg',
      ),
      ImagePage(
        src: 'https://cdn.pixabay.com/photo/2023/01/23/17/28/tree-7739243__340.jpg',
      ),
      ImagePage(
        src: 'https://cdn.pixabay.com/photo/2022/08/17/07/10/strawberries-7391738__340.jpg',
      ),
    ];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          title: Text('pageviewswiper轮播图'),
        ),
        body: SizedBox(
            height: 200,
            child: PageView.builder(
                itemCount: 1000,
                itemBuilder: (context, index) {
                  return list[index%list.length];
                  ///index的值是0-1000,我们想让它以0  1  2  3  0  1  2  3  来无限循环,可以采用这种取余的方式
            })));
  }
}

Flutter轮播图:Swiper与PageView,及PageView的应用_第5张图片

实现类似这样的小点:
Flutter轮播图:Swiper与PageView,及PageView的应用_第6张图片

import 'package:flutter/material.dart';
import 'package:untitled7/ImagePage.dart';

class PageViewSwiperPage extends StatefulWidget {
  const PageViewSwiperPage({Key? key}) : super(key: key);

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

class _PageViewSwiperPageState extends State<PageViewSwiperPage> {

  List<Widget> list=[];

  int _currentIndex=0;

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    list=const[
      ImagePage(
        src: 'https://cdn.pixabay.com/photo/2023/03/25/10/00/bee-7875530__340.jpg',
      ),
      ImagePage(
        src: 'https://cdn.pixabay.com/photo/2023/03/27/11/17/wild-plant-7880509__340.jpg',
      ),
      ImagePage(
        src: 'https://cdn.pixabay.com/photo/2023/01/23/17/28/tree-7739243__340.jpg',
      ),
      ImagePage(
        src: 'https://cdn.pixabay.com/photo/2022/08/17/07/10/strawberries-7391738__340.jpg',
      ),
    ];
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
          title: Text('pageviewswiper轮播图'),
        ),
        body: Stack(
          children: [
            SizedBox(
                height: 200,
                child: PageView.builder(
                  onPageChanged: (index){
                    setState(() {
                      _currentIndex=index % list.length;
                      /*最开始_currentIndex=0,
                      滑动一次后index=1,_currentIndex=1,
                      再滑动一次,index=2,_currentIndex=2
                      再滑动一次,index=3,_currentIndex=3
                      再滑动一次,index=4,_currentIndex=0
                      再滑动一次,index=5,_currentIndex=1
                      再滑动一次,index=6,_currentIndex=2
                      ......如此循环下去
                      * */
                    });
                  },
                    itemCount: 1000,
                    itemBuilder: (context, index) {
                      return list[index%list.length];
                      ///index的值是0-1000,我们想让它以0  1  2  3  0  1  2  3  来无限循环,可以采用这种取余的方式
                    })
            ),
            Positioned(
                left: 0,
                bottom: 20,
                right: 0, //设置left0right0就会占满整行
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.center,
                  children: List.generate(list.length, //循环次数
                      (index) {
                    return Container(
                      margin: EdgeInsets.all(5),  //点和点之间的距离
                      width: 10,
                      height: 10,
                      decoration: BoxDecoration(
                        color: _currentIndex==index?Colors.blue:Colors.grey,
                        shape: BoxShape.circle   //设置成圆
                        //borderRadius: BorderRadius.circular(5)   //设置成圆
                      ),
                    );
                  }).toList(),
                ))
          ],
        ));
  }
}

Flutter轮播图:Swiper与PageView,及PageView的应用_第7张图片

AutomaticKeepAliveClientMixin缓存PageView页面:

import 'package:flutter/material.dart';

class PageViewPage extends StatefulWidget {
  const PageViewPage({Key? key}) : super(key: key);

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

class _PageViewPageState extends State<PageViewPage> with AutomaticKeepAliveClientMixin{
  @override
  Widget build(BuildContext context) {  //默认数据没有缓存,每次滑动都要重新build
    return Scaffold(
      appBar: AppBar(title: Text('title'),),
      body: PageView(
        scrollDirection: Axis.vertical,   //配置滑动方向,默认是水平
        children: [
          Center(
            child: Text('第一屏',style: Theme.of(context).textTheme.headline1,),
          ),
          Center(
            child: Text('第二屏',style: Theme.of(context).textTheme.headline1,),
          ),
        ],
      ),
    );
  }

  @override
  // TODO: implement wantKeepAlive 
  bool get wantKeepAlive => true;  //true表示缓存页面
}

如果页面比较多,缓存会耗费内存

你可能感兴趣的:(flutter,android)