4

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.

2 Answers 2

12

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(),
          ),
        ),
      ),
    );
  }
}
Sign up to request clarification or add additional context in comments.

Comments

0

You can do this with AnimationController. After setup animation controller, you just call the repeat function. The animation will be going to a limitless loop. With AnimationStatusListener you can change color and title text.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.