I would like to create a widget with an animation composed of showing a sequence of images fading in and out with a repeat after complete. Something like this attached animation:
Since I'm new to Flutter, I would like to know what is the best approach to this.
This can be done with AnimatedSwitcher
widget. It's one of Flutter's easy-to-use implicit animation widgets. Its main job is to automatically create a cross-fade transition when its child widget changes.
You can see it in action by changing the string below, and do a hot reload. You will see a cross fade transition for 200 ms:
AnimatedSwitcher(
duration: Duration(milliseconds: 200),
child: Text(
'Hello', // manually change the text here, and hot reload
key: UniqueKey(),
),
)
Once you understand how AnimatedSwitcher
works, you can decide how to loop through the list images. For simplicity, I'm giving you an example using texts, but the idea is the same.
Full source code:
import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: MyHomePage(),
);
}
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
late final Timer timer;
final values = ['A', 'B', 'C', 'D'];
int _index = 0;
@override
void initState() {
super.initState();
timer = Timer.periodic(Duration(seconds: 1), (timer) {
setState(() => _index++);
});
}
@override
void dispose() {
timer.cancel();
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Flutter Demo'),
),
body: Center(
child: AnimatedSwitcher(
duration: Duration(milliseconds: 200),
child: Text(
values[_index % values.length],
key: UniqueKey(),
),
),
),
);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With