Let’s learn how to make a blink text widget in Flutter. To make a blink text we need a stateful class, Timer.periodic() and some strings.
First, we created a _timer object using Timer.periodic()
Timer.periodic() toggles a boolean named _show in every 500 milliseconds, based on the boolean we show or hide the text.
The actual show and hide text happens in by changing the text style.
void main() async {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
title: 'Flutter Demo',
theme: ThemeData(
primaryColor: Colors.blue,
fontFamily: "Lato",
),
home: Scaffold(
backgroundColor: Colors.white,
body: Center(
child: BlinkText(
"great"
)
),
),
);
}
}
class BlinkText extends StatefulWidget {
final String _target;
const BlinkText(this._target, {Key? key}) : super(key: key);
@override
_BlinkTextState createState() => _BlinkTextState();
}
class _BlinkTextState extends State<BlinkText> {
bool _show = true;
Timer? _timer;
@override
void initState() {
_timer = Timer.periodic(const Duration(milliseconds: 500), (_) {
setState(() => _show = !_show);
});
super.initState();
}
@override
Widget build(BuildContext context) => Text(widget._target,
style: _show
? const TextStyle(fontSize: 50, fontWeight: FontWeight.bold)
: const TextStyle(color: Colors.transparent));
@override
void dispose() {
_timer?.cancel();
super.dispose();
}
}