【问题标题】:How can I create a widget with a semi-transparent background and an opaque foreground?如何创建具有半透明背景和不透明前景的小部件?
【发布时间】:2018-05-30 20:13:29
【问题描述】:

我创建了这个颤振小部件,它显示了一个半透明的背景和一个不透明的前景。我使用堆栈来做到这一点。不幸的是,我还必须使用内容来布置背景,否则内容的大小会不正确。

有没有办法让堆栈中的背景知道前景的大小而无需进行两次布局?

typedef void OnTapFn();

class Bubble extends StatelessWidget {
  const Bubble({
    @required this.tapFn,
    @required this.content,
    this.margin = 4.0,
    this.color = Colors.grey,
  });

  final OnTapFn tapFn;
  final double margin;
  final Widget content;
  final Color color;

  @override
  Widget build(BuildContext context) => new GestureDetector(
      onTap: () => tapFn,
      child: new Stack(
        children: <Widget>[
          new Opacity(opacity: 0.5, child: _buildBackground),
          new Container(
              margin: new EdgeInsets.all(margin), //same as the Border width
              child: new Opacity(opacity: 1.0, child: content))
        ],
      ));

  Container get _buildBackground => new Container(
      decoration: new BoxDecoration(
        border: new Border.all(width: margin, color: color),
        borderRadius: const BorderRadius.all(const Radius.circular(30.0)),
      ),
      //placeholder to guarantee that the background is big enough
      child: new Container(
          color: color, child: new Opacity(opacity: 0.0, child: content)));
}

【问题讨论】:

    标签: android flutter


    【解决方案1】:

    如果您想使用 Colors.grey(而不是通过 Colors.fromRGBO 使用其 RGB 等效项),

    你可以指定color: Colors.grey.withOpacity(0.5)

    【讨论】:

    • 你拯救了我的一天。
    【解决方案2】:

    我想你不需要堆栈来实现它。您可以通过为您的小部件指定装饰来直接指定背景。

    例子:

    new Container(
                decoration: new BoxDecoration(
                  border: new Border.all(width: borderWidth ,color: Colors.transparent), //color is transparent so that it does not blend with the actual color specified
                  borderRadius: const BorderRadius.all(const Radius.circular(30.0)),
                  color: new Color.fromRGBO(255, 0, 0, 0.5) // Specifies the background color and the opacity
                ),
              child: _content,
            )
    

    希望有所帮助!

    【讨论】:

      猜你喜欢
      • 2015-11-12
      • 1970-01-01
      • 2011-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-05-29
      相关资源
      最近更新 更多