Flutter实现Android跑马灯及滚动广告

Stella981
• 阅读 1243

简介

本文介绍怎么在Flutter里使用ListView实现Android的跑马灯,然后再扩展一下,实现上下滚动。

Github地址

该小控件已经成功上传到pub.dev,安装方式:

dependencies:
   switcher: ^1.0.0+1

效果图

先上效果图:

垂直模式

Flutter实现Android跑马灯及滚动广告

水平模式

Flutter实现Android跑马灯及滚动广告

上代码

主要有两种滚动模式,垂直模式和水平模式,所以我们定义两个构造方法。 参数分别有滚动速度(单位是pixels/second)、每次滚动的延迟、滚动的曲线变化和children为空的时候的占位控件。

class Switcher {
  const Switcher.vertical({
    Key key,
    @required this.children,
    this.scrollDelta = _kScrollDelta,
    this.delayedDuration = _kDelayedDuration,
    this.curve = Curves.linearToEaseOut,
    this.placeholder,
  })  : assert(scrollDelta != null && scrollDelta > 0 && scrollDelta <= _kMaxScrollDelta),
        assert(delayDuration != null),
        assert(curve != null),
        spacing = 0,
        _scrollDirection = Axis.vertical,
        super(key: key);
  
  const Switcher.horizontal({
    Key key,
    @required this.children,
    this.scrollDelta = _kScrollDelta,
    this.delayedDuration = _kDelayedDuration,
    this.curve = Curves.linear,
    this.placeholder,
    this.spacing = 10,
  })  : assert(scrollDelta != null && scrollDelta > 0 && scrollDelta <= _kMaxScrollDelta),
        assert(delayDuration != null),
        assert(curve != null),
        assert(spacing != null && spacing >= 0 && spacing < double.infinity),
        _scrollDirection = Axis.horizontal,
        super(key: key);
}

实现思路

实现思路有两种:

  • 第一种是用ListView

  • 第二种是用CustomPaint自己画;

这里我们选择用ListView方式实现,方便后期扩展可手动滚动,如果用CustomPaint,实现起来就比较麻烦。

接下来我们分析一下究竟该怎么实现:

垂直模式

首先分析一下垂直模式,如果想实现循环滚动,那么children的数量就应该比原来的多一个,当滚动到最后一个的时候,立马跳到第一个,这里的最后一个实际就是原来的第一个,所以用户不会有任何察觉,这种实现方式在前端开发中应用很多,比如实现PageView的循环滑动,所以这里我们先定义childCount

_initalizationElements() {
  _childCount = 0;
  if (widget.children != null) {
    _childCount = widget.children.length;
  }
  if (_childCount > 0 && widget._scrollDirection == Axis.vertical) {
    _childCount++;
  }
}

children改变的时候,我们重新计算一次childCount

@override
void didUpdateWidget(Switcher oldWidget) {
  var childrenChanged = (widget.children?.length ?? 0) != (oldWidget.children?.length ?? 0);
  if (widget._scrollDirection != oldWidget._scrollDirection || childrenChanged) {
    _initalizationElements();
    _initializationScroll();
  }
  super.didUpdateWidget(oldWidget);
}

这里判断如果是垂直模式,我们就childCount++,接下来,实现一下build方法:

@override
Widget build(BuildContext context) {
  if (_childCount == 0) {
    return widget.placeholder ?? SizedBox.shrink();
  }
  return LayoutBuilder(
    builder: (context, constraints) {
      return ConstrainedBox(
        constraints: constraints,
        child: ListView.separated(
          itemCount: _childCount,
          physics: NeverScrollableScrollPhysics(),
          controller: _controller,
          scrollDirection: widget._scrollDirection,
          padding: EdgeInsets.zero,
          itemBuilder: (context, index) {
            final child = widget.children[index % widget.children.length];
            return Container(
              alignment: Alignment.centerLeft,
              height: constraints.constrainHeight(),
              child: child,
            );
          },
          separatorBuilder: (context, index) {
            return SizedBox(
              width: widget.spacing,
            );
          },
        ),
      );
    },
  );
}

接下来实现垂直滚动的主要逻辑:

_animateVertical(double extent) {
  if (!_controller.hasClients || widget._scrollDirection != Axis.vertical) {
    return;
  }
  if (_selectedIndex == _childCount - 1) {
    _selectedIndex = 0;
    _controller.jumpTo(0);
  }
  _timer?.cancel();
  _timer = Timer(widget.delayedDuration, () {
    _selectedIndex++;
    var duration = _computeScrollDuration(extent);
    _controller.animateTo(extent * _selectedIndex, duration: duration, curve: widget.curve).whenComplete(() {
      _animateVertical(extent);
    });
  });
}

解释一下这段逻辑,先判断ScrollController有没有加载完成,然后当前的滚动方向是不是垂直的,不是就直接返回,然后当前的index是最后一个的时候,立马跳到第一个,index初始化为0,接下来,取消前一个定时器,开一个新的定时器,定时器的时间为我们传进来的间隔时间,然后每间隔widget.delayedDuration的时间滚动一次,这里调用ScrollController.animateTo,滚动距离为每个item的高度乘以当前的索引,滚动时间根据滚动速度算出来:

Duration _computeScrollDuration(double extent) {
  return Duration(milliseconds: (extent * Duration.millisecondsPerSecond / widget.scrollDelta).floor());
}

这里是我们小学就学过的,距离 = 速度 x 时间,所以根据距离和速度我们就可以得出需要的时间,这里乘以Duration.millisecondsPerSecond的原因是转换成毫秒,因为我们的速度是pixels/second

当完成当前滚动的时候,进行下一次,这里递归调用_animateVertical,这样我们就实现了垂直的循环滚动。

水平模式

接下去实现水平模式,和垂直模式类似:

_animateHorizonal(double extent, bool needsMoveToTop) {
  if (!_controller.hasClients || widget._scrollDirection != Axis.horizontal) {
    return;
  }
  _timer?.cancel();
  _timer = Timer(widget.delayedDuration, () {
    if (needsMoveToTop) {
      _controller.jumpTo(0);
      _animateHorizonal(extent, false);
    } else {
      var duration = _computeScrollDuration(extent);
      _controller.animateTo(extent, duration: duration, curve: widget.curve).whenComplete(() {
        _animateHorizonal(extent, true);
      });
    }
  });
}

这里解释一下needsMoveToTop,因为水平模式下,首尾都要停顿,所以我们加个参数判断下,如果是当前执行的滚动到头部的话,needsMoveToTopfalse,如果是已经滚动到了尾部,needsMoveToToptrue,表示我们的下一次的行为是滚动到头部,而不是开始滚动到整个列表。

接下来我们看看在哪里开始滚动。

首先在页面加载的时候我们开始滚动,然后还有当方向和childCount改变的时候,重新开始滚动,所以:

@override
void initState() {
  super.initState();
  _initalizationElements();
  _initializationScroll();
}

@override
void didUpdateWidget(Switcher oldWidget) {
  var childrenChanged = (widget.children?.length ?? 0) != (oldWidget.children?.length ?? 0);
  if (widget._scrollDirection != oldWidget._scrollDirection || childrenChanged) {
    _initalizationElements();
    _initializationScroll();
  }
  super.didUpdateWidget(oldWidget);
}

然后是_initializationScroll方法:

_initializationScroll() {
  SchedulerBinding.instance.addPostFrameCallback((timeStamp) {
    if (!mounted) {
      return;
    }
    var renderBox = context?.findRenderObject() as RenderBox;
    if (!_controller.hasClients || _childCount == 0 || renderBox == null || !renderBox.hasSize) {
      return;
    }
    var position = _controller.position;
    _timer?.cancel();
    _timer = null;
    position.moveTo(0);
    _selectedIndex = 0;
    if (widget._scrollDirection == Axis.vertical) {
      _animateVertical(renderBox.size.height);
    } else {
      var maxScrollExtent = position.maxScrollExtent;
      _animateHorizonal(maxScrollExtent, false);
    }
  });
}

这里在页面绘制完成的时候,我们判断,如果ScrollController没有加载,childCount == 0或者大小没有计算完成的时候直接返回,然后获取position,取消上一个计时器,然后把列表滚到头部,index初始化为0,判断是垂直模式,开始垂直滚动,如果是水平模式开始水平滚动。

这里注意,垂直滚动的时候,每次的滚动距离是每个item的高度,而水平滚动的时候,滚动距离是列表可滚动的最大长度

到这里我们已经实现了Android的跑马灯,而且还增加了垂直滚动,是不是很简单呢。

如有问题、意见和建议,都可以在评论区里告诉我,我将及时修改和参考你的意见和建议,对代码做出优化。

点赞
收藏
评论区
推荐文章
blmius blmius
2年前
MySQL:[Err] 1292 - Incorrect datetime value: ‘0000-00-00 00:00:00‘ for column ‘CREATE_TIME‘ at row 1
文章目录问题用navicat导入数据时,报错:原因这是因为当前的MySQL不支持datetime为0的情况。解决修改sql\mode:sql\mode:SQLMode定义了MySQL应支持的SQL语法、数据校验等,这样可以更容易地在不同的环境中使用MySQL。全局s
Jacquelyn38 Jacquelyn38
2年前
2020年前端实用代码段,为你的工作保驾护航
有空的时候,自己总结了几个代码段,在开发中也经常使用,谢谢。1、使用解构获取json数据let jsonData  id: 1,status: "OK",data: 'a', 'b';let  id, status, data: number   jsonData;console.log(id, status, number )
皕杰报表之UUID
​在我们用皕杰报表工具设计填报报表时,如何在新增行里自动增加id呢?能新增整数排序id吗?目前可以在新增行里自动增加id,但只能用uuid函数增加UUID编码,不能新增整数排序id。uuid函数说明:获取一个UUID,可以在填报表中用来创建数据ID语法:uuid()或uuid(sep)参数说明:sep布尔值,生成的uuid中是否包含分隔符'',缺省为
Stella981 Stella981
2年前
Flutter环境搭建
本文介绍mac上搭建Flutter环境1、Flutter官方提供中国地区镜像地址:https://github.com/flutter/flutter/wiki/UsingFlutterinChina(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fgithub.com%2Ff
Stella981 Stella981
2年前
Android So动态加载 优雅实现与原理分析
背景:漫品Android客户端集成适配转换功能(基于目标识别(So库35M)和人脸识别库(5M)),导致apk体积50M左右,为优化客户端体验,决定实现So文件动态加载.!(https://oscimg.oschina.net/oscnet/00d1ff90e4b34869664fef59e3ec3fdd20b.png)点击上方“蓝字”关注我
Stella981 Stella981
2年前
Golang注册Eureka的工具包goeureka发布
1.简介提供Go微服务客户端注册到Eureka中心。点击:github地址(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fgithub.com%2FSimonWang00%2Fgoeureka),欢迎各位多多star!(已通过测试验证,用于正式生产部署)2.原理
Stella981 Stella981
2年前
Django中Admin中的一些参数配置
设置在列表中显示的字段,id为django模型默认的主键list_display('id','name','sex','profession','email','qq','phone','status','create_time')设置在列表可编辑字段list_editable
Stella981 Stella981
2年前
Flutter自定义一个图片预览页面
本文介绍,怎么用Flutter自定义一个图片预览页面,具有下滑关闭,点击关闭,放大缩小等功能。GitHub地址(https://www.oschina.net/action/GoToLink?urlhttps%3A%2F%2Fgithub.com%2Fchangleibox%2Fpreimage"GitHub地址")该控件已经抽象为一个控件,
Wesley13 Wesley13
2年前
MySQL部分从库上面因为大量的临时表tmp_table造成慢查询
背景描述Time:20190124T00:08:14.70572408:00User@Host:@Id:Schema:sentrymetaLast_errno:0Killed:0Query_time:0.315758Lock_
Python进阶者 Python进阶者
3个月前
Excel中这日期老是出来00:00:00,怎么用Pandas把这个去除
大家好,我是皮皮。一、前言前几天在Python白银交流群【上海新年人】问了一个Pandas数据筛选的问题。问题如下:这日期老是出来00:00:00,怎么把这个去除。二、实现过程后来【论草莓如何成为冻干莓】给了一个思路和代码如下:pd.toexcel之前把这