How to make a Text widget act like marquee when the text overflows in Flutter?
This widget is what i came up with, and I think it serves your needs:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 | class MarqueeWidget extends StatefulWidget { final Widget child; final Axis direction; final Duration animationDuration, backDuration, pauseDuration; MarqueeWidget({ @required this.child, this.direction: Axis.horizontal, this.animationDuration: const Duration(milliseconds: 3000), this.backDuration: const Duration(milliseconds: 800), this.pauseDuration: const Duration(milliseconds: 800), }); @override _MarqueeWidgetState createState() => _MarqueeWidgetState(); } class _MarqueeWidgetState extends State<MarqueeWidget> { ScrollController scrollController; @override void initState() { scrollController = ScrollController(initialScrollOffset: 50.0); WidgetsBinding.instance.addPostFrameCallback(scroll); super.initState(); } @override void dispose(){ scrollController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return SingleChildScrollView( child: widget.child, scrollDirection: widget.direction, controller: scrollController, ); } void scroll(_) async { while (scrollController.hasClients) { await Future.delayed(widget.pauseDuration); if(scrollController.hasClients) await scrollController.animateTo( scrollController.position.maxScrollExtent, duration: widget.animationDuration, curve: Curves.ease); await Future.delayed(widget.pauseDuration); if(scrollController.hasClients) await scrollController.animateTo(0.0, duration: widget.backDuration, curve: Curves.easeOut); } } } |
Its functionality should be pretty obvious. An example implementation would look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 | class FlutterMarqueeText extends StatefulWidget { @override _FlutterMarqueeTextState createState() => _FlutterMarqueeTextState(); } class _FlutterMarqueeTextState extends State<FlutterMarqueeText> { @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text("Flutter Marquee Text"), ), body: Center( child: SizedBox( width: 200.0, child: MarqueeWidget( direction: Axis.horizontal, child: Text( "This text is to long to be shown in just one line"))), )); } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.