求助:如何实现翻页倒计时时钟Widget动画效果
实现打字机式文本动画的方案
你展示的是打字机式文本逐字显示+光标闪烁的动画效果,下面提供无需依赖第三方包的Flutter原生实现方案,避免pub.dev包的兼容问题:
核心实现代码
import 'package:flutter/material.dart'; class TypewriterAnimation extends StatefulWidget { final String targetText; final Duration charDelay; final Duration cursorBlinkInterval; const TypewriterAnimation({ super.key, required this.targetText, this.charDelay = const Duration(milliseconds: 100), this.cursorBlinkInterval = const Duration(milliseconds: 500), }); @override State<TypewriterAnimation> createState() => _TypewriterAnimationState(); } class _TypewriterAnimationState extends State<TypewriterAnimation> with SingleTickerProviderStateMixin { late AnimationController _cursorController; String _currentText = ''; int _charIndex = 0; @override void initState() { super.initState(); // 初始化光标闪烁控制器 _cursorController = AnimationController( vsync: this, duration: widget.cursorBlinkInterval, )..repeat(reverse: true); // 启动逐字打字逻辑 _startTyping(); } void _startTyping() { if (_charIndex < widget.targetText.length) { Future.delayed(widget.charDelay, () { setState(() { _currentText += widget.targetText[_charIndex]; _charIndex++; }); _startTyping(); }); } } @override void dispose() { _cursorController.dispose(); super.dispose(); } @override Widget build(BuildContext context) { return Row( mainAxisSize: MainAxisSize.min, children: [ Text(_currentText), // 闪烁光标 AnimatedBuilder( animation: _cursorController, builder: (context, child) => Opacity( opacity: _cursorController.value > 0.5 ? 1 : 0, child: const Text('|', style: TextStyle(fontWeight: FontWeight.bold)), ), ), ], ); } } // 使用示例 class DemoPage extends StatelessWidget { const DemoPage({super.key}); @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar(title: const Text('打字机动画演示')), body: Center( child: TypewriterAnimation( targetText: '欢迎使用打字机式文本动画效果', charDelay: const Duration(milliseconds: 120), ), ), ); } }
实现说明
- 基于Flutter原生
AnimationController实现光标闪烁,通过递归延迟添加字符实现逐字打字效果 - 无需依赖第三方包,避免版本冲突和运行异常问题
- 可通过
charDelay调整打字速度,cursorBlinkInterval调整光标闪烁频率 - 若需要支持富文本、换行等复杂场景,可结合
RichText修改_currentText的拼接逻辑
内容的提问来源于stack exchange,提问作者Kanu Thakor
相关产品推荐
相关产品推荐

