【flutter】寬度自適應(yīng)滾動(dòng)的text

3d2b7dd9-7e56-4a6b-b48d-2991be48644d.gif

本來是使用第三方CarouselSlider 就能簡單完成需求,但是他無法實(shí)現(xiàn)寬度自適應(yīng),類似多語言的時(shí)候,可能有問題,所以自己寫了一個(gè)。

class TitleSwitcher extends StatefulWidget {
  final List<String> titles;
  final Duration duration;
  final TextStyle? style;

  const TitleSwitcher(
      {super.key, required this.titles, required this.duration, this.style});

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

class _TitleSwitcherState extends State<TitleSwitcher> {
  int _currentIndex = 0;
  late Timer _timer;

  @override
  void initState() {
    super.initState();
    _startTimer();
  }

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

  void _startTimer() {
    _timer = Timer.periodic(widget.duration, (Timer timer) {
      setState(() {
        _currentIndex = (_currentIndex + 1) % widget.titles.length;
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return AnimatedSwitcher(
      duration: Duration(seconds: 1),
      transitionBuilder: (Widget child, Animation<double> animation) {
        final slideInAnimation = Tween<Offset>(
          begin: Offset(0, 1),
          end: Offset(0, 0),
        ).animate(animation);

        final slideOutAnimation = Tween<Offset>(
          begin: Offset(0, -1),
          end: Offset(0, 0),
        ).animate(animation);

        if (child.key == ValueKey(_currentIndex)) {
          return ClipRect(
            child: SlideTransition(
              position: slideInAnimation,
              child: child,
            ),
          );
        } else {
          return ClipRect(
            child: SlideTransition(
              position: slideOutAnimation,
              child: child,
            ),
          );
        }
      },
      child: Text(
        widget.titles[_currentIndex],
        key: ValueKey<int>(_currentIndex),
        style: widget.style ?? TextStyle(fontSize: 24),
      ),
    );
  }
}
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請結(jié)合常識與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容