I have this code which adds each character from a String to a Stream inside a timer creating this effect:
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,
),
);
},
),
),
),
);
}
}
The thing is, instead of a single String, I want to perform this with RichText, where each TextSpan comes from a List of TextSpan with unknown length. This way, each TextSpan would have its own different style and would be animated in sequence (one stream after another).
In example:
List<TextSpan> allSpans = [TextSpan(text: 'This is a ', style: TextStyle(color: Colors.white)), TextSpan(text: 'title', style: TextStyle(color: Colors.red))];
Is it possible to create a separate Stream for each TextSpan? Or is there a better approach?
