我有这样的代码,它将字符串中的每个字符添加到计时器内的流中,以创建此效果:
import 'dart:async';
import 'package:flutter/material.dart';
void main() async {
runApp(
MaterialApp(
home: TextSpanStream(),
),
);
}
class TextSpanStream extends StatefulWidget {
TextSpanStream({Key? key}) : super(key: key);
@override
_TextSpanStreamState createState() => _TextSpanStreamState();
}
class _TextSpanStreamState extends State<TextSpanStream> {
Timer? _timer;
StreamController<String> _textShowController =
StreamController<String>.broadcast();
@override
void initState() {
super.initState();
Future.delayed(Duration(seconds: 1), () => startBroadcast());
}
@override
void dispose() {
_textShowController.close();
_timer?.cancel();
super.dispose();
}
void startBroadcast() {
String title = 'This is a title';
int countLetter = 1;
_timer = Timer.periodic(Duration(milliseconds: 100), (timer) {
_textShowController.add(title.substring(0, countLetter));
countLetter++;
if (countLetter == title.length + 1) {
timer.cancel();
countLetter = 1;
}
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.cyan[900],
body: Center(
child: Container(
color: Colors.black26,
width: 400,
child: StreamBuilder<String>(
stream: _textShowController.stream,
builder: (context, snapshot) {
return Text(
snapshot.hasData ? (snapshot.data ?? '') : '',
style: TextStyle(
color: Colors.white,
fontSize: 18,
),
);
},
),
),
),
);
}
}
问题是,我想用 RichText 执行此操作,而不是单个字符串,其中每个 TextSpan 来自长度未知的 TextSpan 列表。这样,每个 TextSpan 都会有自己不同的样式,并且会按顺序进行动画处理(一个接一个的流)。
例如:
List<TextSpan> allSpans = [TextSpan(text: 'This is a ', style: TextStyle(color: Colors.white)), TextSpan(text: 'title', style: TextStyle(color: Colors.red))];
是否可以为每个 TextSpan 创建单独的 Stream?或者有更好的方法吗?
答案 0 :(得分:1)
您可以创建 TextSpan 并通过要构建的流发送。
col