flutter3.0学习笔记

AnimatedOpacity

Preview
  • AnimatedOpacity(隐式动画)

AnimatedOpacity(隐式动画)

AnimatedOpacity在给定的持续时间内为其孩子的不透明度设置动画。

  • 构造函数
const AnimatedOpacity({
    super.key,
    this.child,
    required this.opacity, // 透明度,0 ~ 1 
    super.curve,// 动画曲线
    required super.duration,// 动画时间
    super.onEnd,// 动画结束的回调方法
    this.alwaysIncludeSemantics = false,//是否总是包含语义信息,默认是 false。这个主要是用于辅助访问的,如果是 true,则不管透明度是多少,都会显示语义信息(可以辅助朗读),这对于视障人员来说会更友好。
  })

例子:

import 'package:flutter/material.dart';

class AnimatedOpacityPage extends StatefulWidget {
  const AnimatedOpacityPage({Key? key}) : super(key: key);

  @override
  State<AnimatedOpacityPage> createState() => _AnimatedOpacityPageState();
}

class _AnimatedOpacityPageState extends State<AnimatedOpacityPage> {
  double _opacity = 1;
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: const Text('AnimatedOpacity'),),
      body: Column(
        children: [
          AnimatedOpacity(
            opacity: _opacity,
            duration: const Duration(seconds: 3),
            curve: Curves.easeIn,
            child: Image.asset('images/liu.webp',width: double.infinity,height: 200, fit: BoxFit.cover,),
          ),
          
          AnimatedOpacity(
            opacity: _opacity,
            duration: const Duration(seconds: 3),
            curve: Curves.elasticInOut,
            child: Container(
              width: double.infinity,
              height: 200,
              color: Colors.amber,
              child: const Center(
                child: Text('Flutter'),
              ),
            ),
          ),
          AnimatedOpacity(
            opacity: _opacity,
            duration: const Duration(seconds: 3),
            curve: Curves.fastOutSlowIn,
            child: Container(
              width: double.infinity,
              height: 200,
              color: Colors.blue,
              child: const Center(
                child: Text('Tehub'),
              ),
            ),
          ),
        ],
      ),
      floatingActionButton: FloatingActionButton(
        onPressed: (){
          setState(() {
            _opacity = _opacity == 0 ? 1 : 0;
          });
        },
        child: Text(_opacity==0?'显示':'隐藏'),
      ),
    );
  }
}

效果: op.gif