Skip to content

[Flutter] How To Fade-in And Fade-out Components

Last Updated on 2021-10-12 by Clay

When we using Flutter to make a mobile application, sometimes we have a need to hide or show some components (or widgets).

Of course we can do it by changing the visibility, changing the color or even deleting the components.

However, these methods will make the components quickly hide/show in an instant, which is not a gorgeous displayed effect.

Yes, no matter which field you need to pay more attention to beauty, even the disappearance or appearance of control components, it is best to add some animation effects.

Because of this, today I will record how to add the fade-in or fade-out effect when the component is showed/hidden.


How to fade-in and fade-out

We need these following components to be example:

  • StatefulWidget: Because it is to make the component render animation, it can not use StatelessWidget
  • AnimatedOpacity widget: A test element with adjustable transparency. A component we want to hide (for example, a Container) needs to be its child
  • FloatingActionButton: A button to control component fade-in or fade-out

AnimatedOpacity has the following most basic parameters to be set:

  • opacity: Transparency, set to 1.0 when displayed (true) and 0.0 when hidden
  • duration: The time to switch the state, the longer the setting, the longer the time for the fade-out/fade-in animation effect

The following is an example:

import 'package:flutter/material.dart';


void main() => runApp(MyApp());


class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: HomePage(),
    );
  }
}


class HomePage extends StatefulWidget {
  @override
  _HomePageState createState() => _HomePageState();
}


class _HomePageState extends State<HomePage> {
  bool visible = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Fade I/O"),
      ),
      body: Center(

        // A test component to test fade in or fade out
        child: AnimatedOpacity(
          opacity: visible ? 1.0 : 0.0,
          duration: Duration(milliseconds: 1000),

          // The test component is a container
          child: Container(
            width: 100,
            height: 100,
            color: Colors.red,
          ),
        ),
      ),

      // Add a new button to control fade in or fade out
      floatingActionButton:
        FloatingActionButton(
          onPressed: () {
            setState(() {
              visible = !visible;
            });
          },
          child: Icon(visible ? Icons.lightbulb_outline : Icons.lightbulb),
        )
    );
  }
}


Output:

https://clay-atlas.com/wp-content/uploads/2021/02/Screen-Recording-2021-02-26-at-4.50.01-PM.mov

References


Read More

Tags:

Leave a ReplyCancel reply

Exit mobile version