How to make text transition by animation upon button press? - flutter

Currently, when opacity = 0 & button is pressed, opacity becomes one. But I would like the button also having the function to turn opacity to zero and back to one when opacity is already one.
How can this be made possible ? Thanks
Im thinking it has something to do with tween? Eg. When the button is pressed, the opacity of the quote turns to zero and back to 1 (duration of one second).
But Im not sure how to write that.
Attached below is the main chunk of the code that's involved in this action:
double opacity1 = 0.0;
String quoteCat1 = List1[Random().nextInt(List1.length)];
void generateConvoTopic1() {
setState(() {
quoteCat1 = List1[Random().nextInt(List1.length)];
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
...
body: ...
AnimatedOpacity(
opacity: opacity1,
duration: Duration(seconds: 1),
child:Text(quoteCat1),
]),
...
ElevatedButton(
...
onPressed: () {
generatequoteCat1();
opacity1 = 1.0;
opacity2 = 0.0;
opacity3 = 0.0;
},),
...

If you only want to switch between two values, you could use a boolean and make your button switch its value. In the toggleOpacity function is also an example of how to animate back the function as #Aayush said using a Future.delayed.
Now if you want more complex animations, or infinite ones, you should use an animationController to have full control of it
See example:
class Demo extends StatefulWidget {
Demo({Key key, this.title}) : super(key: key);
final String title;
#override
_DemoState createState() => _DemoState();
}
class _DemoState extends State<Demo> {
bool visible = true;
var animateBack=false;
void toggleOpacity() {
setState(() {
visible = !visible;
});
if(animateBack)
Future.delayed(Duration(seconds: 1)).then((value) {
setState(() {
visible = !visible;
});
});
}
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: AnimatedOpacity(
opacity: visible ? 1 : 0,
duration: Duration(seconds: 1),
child: Text(
'Now you see me',
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: toggleOpacity,
child: Icon(visible?Icons.wb_sunny:Icons.wb_sunny_outlined),
), // This trailing comma makes auto-formatting nicer for build methods.
);
}
}

Related

How to toggle rive animation when tapped on the animation in flutter

I am a beginner to rive and flutter. I am building a favorite items page in flutter. If there are not anything added to favorites I need to show a riveAnimation on screen. I already implemented almost everything to show the animation on screen. But I need to toggle a jumping animation when user tap on the animation which is really cool. for now I have the animation on 'Idle' mode
You may want to refer to the rive file => Go to Rive. And I renamed Rive stateMachine name to Bird. Everything else is the same.
summary => I want bird to jump when user tap on him :)
The code and the image may be little bit bigger. Sorry about that
class Favourites extends StatefulWidget {
Favourites({Key? key}) : super(key: key);
#override
State<Favourites> createState() => _FavouritesState();
}
class _FavouritesState extends State<Favourites> {
String animation = 'idle';
SMIInput<String>? _birdInput;
Artboard? _birdArtboard;
void jump() {
setState(() {
_birdInput?.value = 'Pressed';
});
}
#override
void initState() {
super.initState();
rootBundle.load('assets/rive/bird.riv').then(
(data) {
final file = RiveFile.import(data);
final artboard = file.mainArtboard;
var controller = StateMachineController.fromArtboard(
artboard,
'Bird',
);
if (controller != null) {
artboard.addController(controller);
_birdInput = controller.findInput('Pressed');
}
setState(() => _birdArtboard = artboard);
},
);
}
#override
Widget build(BuildContext context) {
final favourite = Provider.of<Favourite>(context);
return Scaffold(
backgroundColor: Colors.grey[300],
appBar: const CustomAppBar(title: 'Favourites'),
body: favourite.items.isEmpty
? Center(
child: Column(
children: [
SizedBox(
width: 300,
height: 500,
child: _birdArtboard == null
? const SizedBox()
: Center(
child: GestureDetector(
onTap: () {},
child: Rive(artboard: _birdArtboard!),
),
),
),
NeumorphicButton(),
],
),
)
: CustomGrid(),
);
}
}
If you open/run rive file on rive site, you can find that it is using Trigger variable for jumping and it is using State Machine 1 state machine.
Next thing comes about declaring variable. You need to use SMITrigger data type for this and use StateMachineController to control the animation.
Use .findSMI(..) instead of .findInput() for SMITrigger.
To start animation on trigger, use
trigger?.fire();
I will encourage you to take a look on editor and check input variable type while performing rive animation.
So the full widget that will provide animation is
class Favourites extends StatefulWidget {
const Favourites({Key? key}) : super(key: key);
#override
State<Favourites> createState() => _FavouritesState();
}
class _FavouritesState extends State<Favourites> {
String animation = 'idle';
Artboard? _birdArtboard;
SMITrigger? trigger;
StateMachineController? stateMachineController;
#override
void initState() {
super.initState();
rootBundle.load('assets/rive/bird.riv').then(
(data) {
final file = RiveFile.import(data);
final artboard = file.mainArtboard;
stateMachineController =
StateMachineController.fromArtboard(artboard, "State Machine 1");
if (stateMachineController != null) {
artboard.addController(stateMachineController!);
trigger = stateMachineController!.findSMI('Pressed');
stateMachineController!.inputs.forEach((e) {
debugPrint(e.runtimeType.toString());
debugPrint("name${e.name}End");
});
trigger = stateMachineController!.inputs.first as SMITrigger;
}
setState(() => _birdArtboard = artboard);
},
);
}
void jump() {
trigger?.fire();
}
#override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[300],
body: Center(
child: Column(
children: [
SizedBox(
width: 300,
height: 400,
child: _birdArtboard == null
? const SizedBox()
: Center(
child: GestureDetector(
onTap: () {
jump();
},
child: Rive(artboard: _birdArtboard!),
),
),
),
],
),
));
}
}

Animate widget on creation

I'm very new to Flutter and I'm trying to understand animations.
This widget will slide up from bottom to center when rendered.
It seems to work, but I'm uncertain if this is the way to do it.
So what I want is that every time this Text widget is put on the screen it should animate from bottom to center. I did that by calling a function from WidgetsBinding.instance.addPostFrameCallback that changes the state in the initState .
Is there a better, cleaner way to this?
class AnimatedCenterText extends StatefulWidget {
final String text;
AnimatedCenterText(this.text);
#override
_AnimatedCenterTextState createState() => _AnimatedCenterTextState();
}
class _AnimatedCenterTextState extends State<AnimatedCenterText> {
AlignmentGeometry _alignment = Alignment.bottomCenter;
void _changeAlignment() {
setState(() {
_alignment = Alignment.center;
});
}
void initState() {
super.initState();
WidgetsBinding.instance.addPostFrameCallback((_) {
_changeAlignment();
});
}
#override
Widget build(BuildContext context) {
return AnimatedAlign(
alignment: _alignment,
duration: Duration(milliseconds: 300),
curve: Curves.easeInCubic,
child: Text(
widget.text,
style: TextStyle(fontSize: 28),
),
);
}
}

How to increase the timing of a Fade animation in flutter using a counter method?

I tried to implement a method on my fadeIn animation that increments the time in which each widget its showing. I want to do that automatically, so if i add one more widget, I dont have to manually set the delay of showing it, but just adding the counter method so it increases ++ for each widget. This is what I done so far:
enum AniProps { opacity, translateX }
class FadeIn extends StatefulWidget {
final int delaySecs;
final Widget child;
FadeIn(this.delaySecs, this.child);
#override
_FadeInState createState() => _FadeInState();
}
class _FadeInState extends State<FadeIn> {
#override
Widget build(BuildContext context) {
var counter = 0;
void incrementCounter() {
setState(() {
counter ++;
print('Counter added');
return counter.toInt();
});
}
const durationSecs = 0.5;
const opacityFade = 0.0;
const translateXFade = 130.0;
final tween = MultiTween<AniProps>()
..add(AniProps.opacity, opacityFade.tweenTo(1.0))
..add(AniProps.translateX, translateXFade.tweenTo(0.0));
return PlayAnimation<MultiTweenValues<AniProps>>(
delay: (widget.delaySecs).round().seconds,
duration: durationSecs.seconds,
tween: tween,
child: widget.child,
builder: (context, child, value) => Opacity(
opacity: value.get(AniProps.opacity),
child: Transform.translate(
offset: Offset(value.get(AniProps.translateX), 0),
child: child,
),
),
);
}
}
Its not really working because i cannot wrap my widgets with a method:
Fade in (increasecounte,
container(................))
Please help.

Update SnackBar content in Flutter

I have a button that displays a SnackBar (or toast) before moving to the next page. I have a countdown and after 5 seconds I push Page2.
RaisedButton(
onPressed: () {
_startTimer();
final snackBar = SnackBar(
behavior: SnackBarBehavior.floating,
content: Text(
'Prepare yourself to start in ${widget._current.toString()}!'), // doesn't work here
duration: new Duration(seconds: widget._start),
action: SnackBarAction(
label: widget._current.toString(), // and neither does here
onPressed: () {
// Some code to undo the change.
},
),
);
Scaffold.of(context).showSnackBar(snackBar);
},
child: Text(
"I'm ready",
style: TextStyle(fontSize: 20),
),
),
Nothing to see on the countdown but I'll paste it just in case:
void _startTimer() {
CountdownTimer countDownTimer = new CountdownTimer(
new Duration(seconds: widget._start),
new Duration(seconds: 1),
);
var sub = countDownTimer.listen(null);
sub.onData((duration) {
setState(() {
widget._current = widget._start - duration.elapsed.inSeconds;
});
});
sub.onDone(() {
print("Done");
sub.cancel();
});
}
So if I display the countdown somewhere else (inside a Text for example) it works but it seems that the SnackBar doesn't change its contain, it always get the max number of the countdown.
you need to implement a custom widget with countdown logic in side for the content field of snackbar, like this:
class TextWithCountdown extends StatefulWidget {
final String text;
final int countValue;
final VoidCallback? onCountDown;
const TextWithCountdown({
Key? key,
required this.text,
required this.countValue,
this.onCountDown,
}) : super(key: key);
#override
_TextWithCountdownState createState() => _TextWithCountdownState();
}
class _TextWithCountdownState extends State<TextWithCountdown> {
late int count = widget.countValue;
late Timer timer;
#override
void initState() {
super.initState();
timer = Timer.periodic(Duration(seconds: 1), _timerHandle);
}
#override
void dispose() {
timer.cancel();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Container(
child: Text("[$count] " + widget.text),
);
}
void _timerHandle(Timer timer) {
setState(() {
count -= 1;
});
if (count <= 0) {
timer.cancel();
widget.onCountDown?.call();
}
}
}
That is because the snack bar is built once, when the button is clicked. When the state updates, it rebuilds the widget tree according to the changes. The snack bar initially isn't in the widget tree, so it doesn't update.
Try to use stack and show a snack bar, and then you should be able to manipulate it however you need.
Hope it helps.
Update SnackBar Content
SnackBar content can be updated/rebuilt while it's visible by making its content: widget dynamic.
In the code sample below we're using a ValueNotifier and ValueListenableBuilder to dynamically rebuild the content of the SnackBar whenever ValueNotifier is given a new value.
(There are many ways to to maintain state values & rebuild widgets when it changes, such as RiverPod, GetX, StreamBuilder, etc. This example uses the Flutter native ValueListenableBuilder.)
When running this Flutter page, click the FAB to show the SnackBar, then click on the center text to update the SnackBar's content (multiple times if you like).
Example
Use SnackBarUpdateExample() widget in your MaterialApp home: argument to try this example in an emulator or device.
class SimpleCount {
int count = 0;
}
class SnackBarUpdateExample extends StatelessWidget {
static const _initText = 'Initial text here';
/// This can be "listened" for changes to trigger rebuilds
final ValueNotifier<String> snackMsg = ValueNotifier(_initText);
final SimpleCount sc = SimpleCount();
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('SnackBar Update'),
),
/// ↓ Nested Scaffold not necessary, just prevents FAB being pushed up by SnackBar
body: Scaffold(
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Text('Click FAB to show SnackBar'),
SizedBox(height: 20,),
Text('Then...'),
SizedBox(height: 20,),
InkWell(
child: Text('Click → here ← to update SnackBar'),
onTap: () {
sc.count++;
snackMsg.value = "Hey! It changed! ${sc.count}";
},
), /// When snackMsg.value changes, the ValueListenableBuilder
/// watching this value, will call its builder function again,
/// and update its SnackBar content widget
],
),
),
floatingActionButton: FloatingActionButton(
child: Icon(Icons.play_arrow),
onPressed: () => _showSnackBar(context),
),
),
);
}
void _showSnackBar(BuildContext context) {
var _controller = ScaffoldMessenger.of(context).showSnackBar(
SnackBar(content: SnackContent(snackMsg))
);
/// This resets the snackBar content when it's dismissed
_controller.closed.whenComplete(() {
snackMsg.value = _initText;
sc.count = 0;
});
}
}
/// The ValueListenableBuilder rebuilds whenever [snackMsg] changes.
class SnackContent extends StatelessWidget {
final ValueNotifier<String> snackMsg;
SnackContent(this.snackMsg);
#override
Widget build(BuildContext context) {
/// ValueListenableBuilder rebuilds whenever snackMsg value changes.
/// i.e. this "listens" to changes of ValueNotifier "snackMsg".
/// "msg" in builder below is the value of "snackMsg" ValueNotifier.
/// We don't use the other builder args for this example so they are
/// set to _ & __ just for readability.
return ValueListenableBuilder<String>(
valueListenable: snackMsg,
builder: (_, msg, __) => Text(msg));
}
}

Show modal bottom sheet with custom animation

I was playing around with showModalBottomSheet() in Flutter and I was thinking about changing the default slide from bottom animation. Looking throught flutter documentation I saw that there is in fact a BottomSheet class that accept animation as parameters but, accordingly to the page, showModalBottomSheet() is preferrable.
Is possible to control the animation in some way? I just need to change the default curve and duration.
Thanks
You can use the AnimationController drive method to modify the animation curve, and duration and reverseDuration to set how long the animation will go on. These can be declared on your initState() if you're using a StatefulWidget.
late AnimationController controller;
#override
initState() {
super.initState();
controller = BottomSheet.createAnimationController(this);
// Animation duration for displaying the BottomSheet
controller.duration = const Duration(seconds: 1);
// Animation duration for retracting the BottomSheet
controller.reverseDuration = const Duration(seconds: 1);
// Set animation curve duration for the BottomSheet
controller.drive(CurveTween(curve: Curves.easeIn));
}
Then configure the BottomSheet transtionAnimationController
showModalBottomSheet(
transitionAnimationController: controller,
builder: (BuildContext context) {
return ...
}
)
Here's a sample that you can try out.
import 'package:flutter/material.dart';
class BottomSheetAnimation extends StatefulWidget {
const BottomSheetAnimation({Key? key}) : super(key: key);
#override
_BottomSheetAnimationState createState() => _BottomSheetAnimationState();
}
class _BottomSheetAnimationState extends State<BottomSheetAnimation>
with TickerProviderStateMixin {
late AnimationController controller;
#override
initState() {
super.initState();
controller = BottomSheet.createAnimationController(this);
// Animation duration for displaying the BottomSheet
controller.duration = const Duration(seconds: 1);
// Animation duration for retracting the BottomSheet
controller.reverseDuration = const Duration(seconds: 1);
// Set animation curve duration for the BottomSheet
controller.drive(CurveTween(curve: Curves.easeIn));
}
#override
void dispose() {
controller.dispose();
super.dispose();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'BottomSheet',
home: Scaffold(
appBar: AppBar(
title: const Text('BottomSheet'),
),
body: Center(
child: TextButton(
child: const Text("Show bottom sheet"),
onPressed: () {
showModalBottomSheet(
context: context,
transitionAnimationController: controller,
builder: (BuildContext context) {
return const SizedBox(
height: 64,
child: Text('Your bottom sheet'),
);
},
);
},
),
),
),
);
}
}
Demo