Dear All,
I am trying to do an automatic animation for Animated switcher between two widgets (Text & Image)... I need the animation to start & repeat automatically without the press of a button... I made this code but it is not working .... please help
```
class SimpleTry extends StatefulWidget {
const SimpleTry({Key? key}) : super(key: key);
@override
_SimpleTryState createState() => _SimpleTryState();
}
class _SimpleTryState extends State<SimpleTry> {
int index = 0;
final widgets = [
const FirstWidget(),
const SecondWidget(),
];
Timer? timer;
@override
void initState() {
Timer.periodic(const Duration(seconds: 1), (Timer t) {
final isLastIndex = index == widgets.length - 1;
setState(() => index = isLastIndex ? 0 : index++);
});
}
@override
void dispose() {
timer?.cancel();
dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
body: SafeArea(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: [
AnimatedSwitcher(
duration: const Duration(seconds: 1),
child: widgets[index],
),
],
),
),
);
}
}
class SecondWidget extends StatelessWidget {
const SecondWidget({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return Image.asset(
'images/u trap.png',
width: 150,
height: 150,
key: const Key('1'),
);
}
}
class FirstWidget extends StatelessWidget {
const FirstWidget({
Key? key,
}) : super(key: key);
@override
Widget build(BuildContext context) {
return const Text(
'Hi',
key: Key('2'),
);
}
}
```