Flutter中实现字体跑马灯

在业务需求开发过程中,经常有需要用到跑马灯效果来展示一些提醒文案,达到醒目的效果,在Flutter中要实现跑马灯的效果,需要借助Timer进行实现。

完整实现代码如下:

class MarqueeText extends StatefulWidget {
  final String text;
  final TextStyle style;
  final double scrollSpeed;

  MarqueeText({
    required this.text,
    required this.style,
    this.scrollSpeed = 50.0, // pixels per second
  });

  @override
  _MarqueeTextState createState() => _MarqueeTextState();
}

class _MarqueeTextState extends State<MarqueeText>
    with SingleTickerProviderStateMixin {
  ScrollController _scrollController = ScrollController();
  late Timer _timer;

  @override
  void initState() {
    super.initState();
    WidgetsBinding.instance.addPostFrameCallback((_) {
      _startMarquee();
    });
  }

  @override
  void dispose() {
    _timer.cancel();
    _scrollController.dispose();
    super.dispose();
  }

  void _startMarquee() {
    _timer = Timer.periodic(Duration(milliseconds: 16), (Timer timer) {
      if (_scrollController.hasClients) {
        final maxScrollExtent = _scrollController.position.maxScrollExtent;
        final currentScroll = _scrollController.position.pixels;
        final delta =
            widget.scrollSpeed * 0.016; // 0.016 is the frame time (16ms)

        if (currentScroll + delta >= maxScrollExtent) {
          _scrollController.jumpTo(0.0);
        } else {
          _scrollController.animateTo(currentScroll + delta,
              duration: Duration(milliseconds: 16), curve: Curves.linear);
        }
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return LayoutBuilder(
      builder: (context, constraints) {
        return SingleChildScrollView(
          controller: _scrollController,
          scrollDirection: Axis.horizontal,
          child: Row(
            children: [
              _buildText(),
              _buildText(), // duplicate the text for seamless scrolling
            ],
          ),
        );
      },
    );
  }

  Widget _buildText() {
    return Text(
      widget.text,
      style: widget.style,
    );
  }
}

使用时:

 MarqueeText(
              text: 'Hello Flutter this is Warning Test',
              style: TextStyle(fontSize: 14, color: AppColor.mainColor),
              scrollSpeed: 20,
            )

即可实现一个简单的跑马灯效果,可根据示例,结合自己的项目进行自定义扩展改造,达到项目所需效果。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值