Flutter Building a Complete Application Manual - Animation

Fade widget

As UI developers, we often need to show and hide elements on the screen. However, popping elements quickly on or off screen can be disconcerting for end users. Instead, we can fade elements in and out with opacity animations to create a smooth experience.

In Flutter, we can use the AnimatedOpacity widget to accomplish this task.

route

  • Show a box to fade in and out
  • Define a StatefulWidget
  • Show button to toggle visibility
  • Fade in and out of the box

1. Show a box to fade in and out

First, we need something to fade in and out! In this example, we will draw a green box on the screen.

new Container(
  width: 200.0,
  height: 200.0,
  color: Colors.green,
);

2. Define a StatefulWidget

Now that we have a green box to animate, we need a way to know if the box is visible or not. For this purpose, we can use a StatefulWidget .

StatefulWidget is the class that creates State objects. The State object holds some data about our application and provides methods to update the data. When we update data, we can also use Flutter to rebuild our UI with those changes.

In our case, we will have a piece of data: a boolean value indicating whether the button is visible or invisible.

In order to construct a StatefulWidget , we need to create two classes: a StatefulWidget and a corresponding State class. Pro tip: The Flutter plugin for Android Studio and VSCode contains stable snippets that generate this code quickly!

// The StatefulWidget's job is to take in some data and create a State class.
// In this case, our Widget takes in a title, and creates a _MyHomePageState.
class MyHomePage extends StatefulWidget {
  final String title;

  MyHomePage({Key key, this.title}) : super(key: key);

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

// The State class is responsible for two things: holding some data we can 
// update and building the UI using that data.
class _MyHomePageState extends State<MyHomePage> {
  // Whether the green box should be visible or invisible
  bool _visible = true;

  @override
  Widget build(BuildContext context) {
    // The green box will go here with some other Widgets!
  }
}

3. Display a button to toggle visibility

Now that we have some data to determine if our green box should be visible or invisible, we need a way to update this data. In our case, we want to hide the box if it is visible. If the box is hidden, we want to show it!

For this purpose, we will display a button. When the user presses the button, we change the boolean value from true to false , or false to true . We need to make changes using setState , which is a method in the State class. This will let Flutter know that it needs to rebuild the part.

Note: For more information on handling user input, see the Handling Gestures section of the recipe book.

new FloatingActionButton(
  onPressed: () {
    // Make sure we call setState! This will tell Flutter to rebuild the
    // UI with our changes!
    setState(() {
      _visible = !_visible;
    });
  },
  tooltip: 'Toggle Opacity',
  child: new Icon(Icons.flip),
);

4. Fade in and out of the box

We have a green box on the screen. We have a button to toggle visibility to true or false . So how do we fade the box in and out? With the AnimatedOpacity widget!

The AnimatedOpacity widget requires three parameters:

  • opacity : A value from 0.0 (invisible) to 1.0 (fully visible).
  • duration : how long the animation will take to complete
  • child : The widget to be animated. In our case, the green box.
new AnimatedOpacity(
  // If the Widget should be visible, animate to 1.0 (fully visible). If
  // the Widget should be hidden, animate to 0.0 (invisible).
  opacity: _visible ? 1.0 : 0.0,
  duration: new Duration(milliseconds: 500),
  // The green box needs to be the child of the AnimatedOpacity
  child: new Container(
    width: 200.0,
    height: 200.0,
    color: Colors.green,
  ),
);

complete example

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    final appTitle = 'Opacity Demo';
    return new MaterialApp(
      title: appTitle,
      home: new MyHomePage(title: appTitle),
    );
  }
}

// The StatefulWidget's job is to take in some data and create a State class.
// In this case, our Widget takes in a title, and creates a _MyHomePageState.
class MyHomePage extends StatefulWidget {
  final String title;

  MyHomePage({Key key, this.title}) : super(key: key);

  @override
  _MyHomePageState createState() => new _MyHomePageState();
}

// The State class is responsible for two things: holding some data we can
// update and building the UI using that data.
class _MyHomePageState extends State<MyHomePage> {
  // Whether the green box should be visible or invisible
  bool _visible = true;

  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      appBar: new AppBar(
        title: new Text(widget.title),
      ),
      body: new Center(
        child: new AnimatedOpacity(
          // If the Widget should be visible, animate to 1.0 (fully visible). If
          // the Widget should be hidden, animate to 0.0 (invisible).
          opacity: _visible ? 1.0 : 0.0,
          duration: new Duration(milliseconds: 500),
          // The green box needs to be the child of the AnimatedOpacity
          child: new Container(
            width: 200.0,
            height: 200.0,
            color: Colors.green,
          ),
        ),
      ),
      floatingActionButton: new FloatingActionButton(
        onPressed: () {
          // Make sure we call setState! This will tell Flutter to rebuild the
          // UI with our changes!
          setState(() {
            _visible = !_visible;
          });
        },
        tooltip: 'Toggle Opacity',
        child: new Icon(Icons.flip),
      ), // This trailing comma makes auto-formatting nicer for build methods.
    );
  }
}

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=324381555&siteId=291194637