flutter不透明组件Opacity和AnimatedOpac

2020-08-13  本文已影响0人  一叠纸船

这个组件很简单,也一目了然,主要用于控制子节点的不透明度。应用场景除了满足常规的UI 效果还常常用做不可见的占位组件使用。

可以定义的属性除了必须指定的opacity之外,只有alwaysIncludeSemantic属性可以指定对应的值,需要赋bool类型的,默认是false。如果是true,即这个组件包含子节点的Semantics信息。这个Semantics用于描述应用程序,主要帮助视障人士使用。

我写了一个简单的例子:

      Column(
        children: <Widget>[
          Container(
            height: 100,
            color: Colors.red,
          ),
          Opacity(
            opacity: 0.0,
            child: Container(
              height: 100,
              color: Colors.blue,
            ),
          ),
          Opacity(
            opacity: 0.5,
            child: Container(
              height: 100,
              color: Colors.yellow,
            ),
          ),
          Container(
            height: 100,
            color: Colors.orange,
          )
        ],
      )

效果如下:

flutter_opacity.jpg

AnimatedOpacity就是Opacity的动画组件,使用起来也很简单,下面是示例代码:

import 'package:flutter/material.dart';

class OpacityScreen extends StatefulWidget {
  OpacityScreen({Key key}) : super(key: key);

  @override
  _OpacityScreenState createState() => _OpacityScreenState();
}

class _OpacityScreenState extends State<OpacityScreen> {
  bool normal = true;

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text('Opacity')),
      body: Column(
        children: <Widget>[
          Container(
            height: 100,
            color: Colors.red,
          ),
          AnimatedOpacity(
            opacity: normal ? 0.0 : 1.0,
            duration: Duration(milliseconds: 500),
            child: Container(
              height: 100,
              color: Colors.blue,
            ),
          ),
          Opacity(
            opacity: 0.5,
            child: Container(
              height: 100,
              color: Colors.yellow,
            ),
          ),
          Container(
            height: 100,
            color: Colors.orange,
          )
        ],
      ),
      floatingActionButton: FloatingActionButton(
        child: Text('switch'),
        onPressed: () {
          setState(() {
            normal = !normal;
          });
        },
      ),
    );
  }
}

效果图如下:


animated_opacity.gif

这个系列的文章是根据flutter 的 Widget of the week来做的,欢迎大家斧正。

上一篇 下一篇

猜你喜欢

热点阅读