Flutter中实现整个App变为灰色

本文介绍了如何在Flutter中通过ColorFiltered widget实现整个App变为灰色,以此纪念重要日期。只需将ColorFiltered包裹在全局根widget下,设置颜色过滤器为灰色,即可一键变灰。此功能虽然简单,但其背后的意义深远。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

前言

为了让更多的人永远记住12月13日,各大厂都在这一天将应用变灰了。

image-20211213081824100

那么接下来我们看一下Flutter是如何实现的。

Flutter中实现整个App变为灰色

在Flutter中实现整个App变为灰色是非常简单的,

只需要在最外层的控件上包裹ColorFiltered,用法如下:

ColorFiltered(颜色过滤器)

看名字就知道是增加颜色滤镜效果的,

ColorFiltered(
      colorFilter:ColorFilter.mode(Colors.grey, BlendMode.color),
      child: child,
    );

将上面代码放到全局根widget下,即可设置全部页面颜色变灰

通过colorFilter可设置某种颜色过滤,比如变灰设置灰色即可,以及颜色混合模式
ColorFiltered 小部件继承SingleChildRenderObjectWidget,因此会提供一个child子布局,这里可以放置想要过滤颜色的页面;

最终我们就合成一张这样带滤镜效果

追踪源码

我我们持续追踪源码到 RenderImage 类中,可以看到最终也是创建了一个 ColorFilter

class ColorFiltered extends SingleChildRenderObjectWidget {
  /// Creates a widget that applies a [ColorFilter] to its child.
  ///
  /// The [colorFilter] must not be null.
  const ColorFiltered({required this.colorFilter, Widget? child, Key? key})
      : assert(colorFilter != null),
        super(key: key, child: child);

  /// The color filter to apply to the child of this widget.
  final ColorFilter colorFilter;

  @override
  RenderObject createRenderObject(BuildContext context) => _ColorFilterRenderObject(colorFilter);

  @override
  void updateRenderObject(BuildContext context, RenderObject renderObject) {
    (renderObject as _ColorFilterRenderObject).colorFilter = colorFilter;
  }

  @override
  void debugFillProperties(DiagnosticPropertiesBuilder properties) {
    super.debugFillProperties(properties);
    properties.add(DiagnosticsProperty<ColorFilter>('colorFilter', colorFilter));
  }
}

设置前

image-20211213081150413

设置后

image-20211213081202975

功能就这样实现了,功能简单,意义不凡。

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

坚果的博客

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值