我有文字:hi ho mi lo tu bo so ad wy
。我想创建一个功能,在两秒钟后,下两个字母的颜色从黑色变为红色。示例:我显示所有单词:hi ho mi lo tu bo so ad wy
和 hi
是红色的。两秒后,hi
变黑,ho
变红。在接下来的两秒后,ho
为黑色,mi
为红色等等。我该怎么做?
在颤动一段时间后更改文本的颜色部分
•
问答
zgyanfeng 回答:在颤动一段时间后更改文本的颜色部分
希望这是你想要的东西,如果你想要一些改变,请告诉我。(gif 动画 7 倍速)
完整的小部件。
import 'dart:async';
import 'package:flutter/material.dart';
class FancyText extends StatefulWidget {
FancyText({Key? key}) : super(key: key);
@override
_FancyTextState createState() => _FancyTextState();
}
class _FancyTextState extends State<FancyText> {
final _normalStyle = TextStyle(
color: Colors.black,fontSize: 24,);
final _redStyle = TextStyle(
color: Colors.red,);
int redIndex = 0;
late Timer timer;
@override
void initState() {
super.initState();
timer = Timer.periodic(Duration(seconds: 2),(timer) {
setState(() {
redIndex++;
if (redIndex > 8) redIndex = 0;
});
print("rebuild");
});
}
@override
void dispose() {
timer.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Text.rich(
TextSpan(children: [
TextSpan(
text: "hi ",style: redIndex == 0 ? _redStyle : _normalStyle,),TextSpan(
text: "ho ",style: redIndex == 1 ? _redStyle : _normalStyle,TextSpan(
text: "mi ",style: redIndex == 2 ? _redStyle : _normalStyle,TextSpan(
text: "lo ",style: redIndex == 3 ? _redStyle : _normalStyle,TextSpan(
text: "tu ",style: redIndex == 4 ? _redStyle : _normalStyle,TextSpan(
text: "bo ",style: redIndex == 5 ? _redStyle : _normalStyle,TextSpan(
text: "so ",style: redIndex == 6 ? _redStyle : _normalStyle,TextSpan(
text: "ad ",style: redIndex == 7 ? _redStyle : _normalStyle,TextSpan(
text: "wy ",style: redIndex == 8 ? _redStyle : _normalStyle,]),);
}
}
,
可以用 Future.delayed 来完成。 通过编辑它在 future.delayed 中写入。每两秒更换一次。更改颜色时更改颜色。
if(a==1){ ..... a=0; }别的{ ... a=1; } 当 a 为 0 时,a 在 2 秒后变为 1。这样你就会得到两种不同的状态。