美文网首页
Flutter -容器渐变(Fade)

Flutter -容器渐变(Fade)

作者: StevenHu_Sir | 来源:发表于2020-03-16 16:53 被阅读0次

话不多说先上效果图

容器渐变效果.gif

思路分析

AnimatedBuilder + Opacity
通过设置透明度以及reverse实现无限渐变效果

源码如下:

/// 渐变动画
///
/// created by hujintao
/// created at 2019-12-18
//
import 'package:flutter/material.dart';

class FadeWrapper extends StatefulWidget {
  final Widget child;

  bool isFade;
  final AnimationController controller;

  FadeWrapper({
    Key key,
    this.child,
    this.controller,
    this.isFade = false,
  }) : super(key: key);

  static stop() {
    FadeWrapper().controller.stop();
  }

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

class _FadeWrapperState extends State<FadeWrapper>
    with SingleTickerProviderStateMixin {
  Animation<double> animation;
  AnimationController controller;

  initState() {
    super.initState();
    controller = AnimationController(
      duration: Duration(seconds: 5),
      vsync: this,
    );
    animation = new Tween(begin: 0.0, end: 1.0).animate(controller);
    controller.repeat(reverse: true);
  }

  @override
  Widget build(BuildContext context) {
    return this.widget.isFade
        ? AnimatedBuilder(
        animation: animation,
        builder: (BuildContext ctx, Widget child) {
          return Opacity(
            opacity: animation.value,
            child: this.widget.child != null
                ? this.widget.child
                : Container(
              child: Center(
                child: Text('透明 '),
              ),
              width: 50,
              height: 50,
              color: Colors.red,
            ),
          );
        })
        : this.widget.child ?? Container();
  }

  @override
  void dispose() {
    // 释放资源
    controller.dispose();
    super.dispose();
  }
}

使用

FadeWrapper(
    child: Row(
      children: <Widget>[
        Container(
          margin: EdgeInsets.only(top: 50),
          child: Center(
            child: Text('渐变哦',style: TextStyle(fontSize: 36),),
          ),
          width: 200,
          height: 200,
          color: Colors.lightBlue,
        )
      ],
      mainAxisAlignment: MainAxisAlignment.center,
    ),
    isFade: true,
  )

相关文章

网友评论

      本文标题:Flutter -容器渐变(Fade)

      本文链接:https://www.haomeiwen.com/subject/rnlnehtx.html