Reputation: 813
I am trying to have some text show (or quickly fade in) as a result of user action (e.g. button click), and after a second fade out without user action. I understand that fading is accomplished by AnimatedOpacity class with opacity being set by a state variable, however it's not clear to me how to accomplish this particular scenario. Many thanks.
Upvotes: 0
Views: 1561
Reputation: 1573
first, text its show it self while not fade its can be considered animated too, or create some async function
check this code :
import 'package:flutter/material.dart';
class FadeTextAuto extends StatefulWidget {
const FadeTextAuto({Key? key}) : super(key: key);
@override
_FadeTextAutoState createState() => _FadeTextAutoState();
}
class _FadeTextAutoState extends State<FadeTextAuto> with SingleTickerProviderStateMixin{
late Animation _animationFadeInOut;
late AnimationController _animationController;
bool _textShouldPlay = false;
late Animation _animationText;
String info = "This text appear in";
@override
void initState() {
super.initState();
_animationController = AnimationController(vsync: this, duration: const Duration(milliseconds: 2000));
_animationFadeInOut = Tween<double>(
begin: 0.0, end: 1.0).animate(CurvedAnimation(parent: _animationController, curve: Curves.linear));
_animationText = StepTween(
begin: 1, end: 3
).animate(CurvedAnimation(parent: _animationController, curve: Curves.linear));
}
@override
Widget build(BuildContext context) {
return Material(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
TextButton(onPressed: (){
setState(() {
info = "This text appear in";
_textShouldPlay = false;
});
print(_animationText.value);
_animationController.forward().then((value){
if(mounted){
setState(() {
_textShouldPlay = true;
info = "Hey read this Information";
});
Future.delayed(const Duration(milliseconds: 2000),(){
//wait a little for text can be read
if(mounted){
setState(() {
_textShouldPlay = false;
info = "this Text will be disappear in";
});
}
}).then((value){
if(mounted){
_animationController.reverse();
}
});
}
});
}, child: const Text("User Click")),
AnimatedBuilder(
animation: _animationController,
builder: (context, child){
return Opacity(
opacity: _animationFadeInOut.value,
child: Text(
"$info ${_textShouldPlay?"":_animationText.value} ", style: const TextStyle(color: Colors.cyan, fontSize: 20),
),
);
},
),
],
),
);
}
@override
void dispose() {
_animationController.dispose();
super.dispose();
}
}
Upvotes: 1