Flutter 逐字改变文字的颜色

200 阅读1分钟

1.主要思路就是定时器改变文字的颜色;

import 'dart:async';
import 'package:flutter/material.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: MyAnimatedText(),
    );
  }
}

class MyAnimatedText extends StatefulWidget {
  @override
  _MyAnimatedTextState createState() => _MyAnimatedTextState();
}

class _MyAnimatedTextState extends State<MyAnimatedText> {
  late List<String> _text;
  late List<Color> _colors;
  late Timer _timer;
  int _currentIndex = 0;

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

    _text = "阿达水陆大会阿达说的卡啥的颗粒剂啊四大皆空啊橘势大好按实际撒大街上".split("");
    _colors = List<Color>.filled(_text.length, Colors.grey);

    _timer = Timer.periodic(Duration(milliseconds: 100), (timer) {
      if (_currentIndex < _text.length) {
        setState(() {
          _colors[_currentIndex] = Colors.red;
          _currentIndex++;
        });
      } else {
        _timer.cancel();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Animated Text'),
      ),
      body: Center(
        child: Wrap(
          children: List.generate(_text.length, (index) {
            return Padding(
              padding: EdgeInsets.all(4),
              child: Text(
                _text[index],
                style: TextStyle(
                  fontSize: 20,
                  color: _colors[index],
                ),
              ),
            );
          }),
        ),
      ),
    );
  }

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