1、背景:
使用三方组件在首页做个跑马灯效果,隔一段时间首页会闪一下,估计是三方组件有内存泄露。趁有空自己写个简单跑马灯效果。
2、效果:
3、调用方法:
将下方代码copy到项目文件内,引用文件,调用构建方法
import 'package:clmd_flutter/components/marquee.dart';
Marquee(child: Row(children: [Text('Flutter跑马灯效果实现-作者:clmd。后面跟点测试内容'),Icon(Icons.play_arrow),Text('当然可以也组合其他显示控件咯',style: TextStyle(color: Colors.red),)],),speed: 10,)
文件内实现:
import 'package:flutter/material.dart';class Marquee extends StatefulWidget {const Marquee({required this.child, this.speed = 10, Key? key}): super(key: key);final Widget child;final int speed; _MarqueeState createState() => _MarqueeState();
}class _MarqueeState extends State<Marquee> with SingleTickerProviderStateMixin {late AnimationController _controller;late Animation<double> _animation;late ScrollController _scrctrl;SingleChildScrollView? _scrollView;double _space = 0;void initState() {super.initState();_scrctrl = ScrollController();_controller = AnimationController(vsync: this, duration: Duration(seconds: widget.speed));_animation = Tween(begin: 0.1,end: 100.0,).animate(_controller);_animation.addListener(() {if (_scrctrl.hasClients) {if (_scrollView != null && _scrctrl.position.hasContentDimensions) {var index = _animation.value / 100;_scrctrl.jumpTo(index * _scrctrl.position.maxScrollExtent);}if (_scrctrl.position.hasViewportDimension && _space == 0) {setState(() {_space = _scrctrl.position.viewportDimension;});}}});_controller.repeat();}Widget build(BuildContext context) {_scrollView = SingleChildScrollView(controller: _scrctrl,scrollDirection: Axis.horizontal,child: _scrctrl.hasClients? Row(children: [SizedBox(width: _space,),widget.child,SizedBox(width: _space,),],): const SizedBox(),);return _scrollView ?? Column();}void dispose() {_controller.dispose();super.dispose();}
}