Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create chained flutter animation with multiple images

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:

flutter animation

Since I'm new to Flutter, I would like to know what is the best approach to this.

like image 924
Mihai Grescenko Avatar asked Sep 18 '25 21:09

Mihai Grescenko


1 Answers

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(),
          ),
        ),
      ),
    );
  }
}
like image 124
user1032613 Avatar answered Sep 21 '25 20:09

user1032613