如何创建具有半透明背景和不透明前景的窗口小部件?

时间:2017-12-17 04:59:24

标签: android flutter

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

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

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)));
}

2 个答案:

答案 0 :(得分:4)

I suppose you'd not need a stack to achieve it. You can directly specify the background by specifying the decoration for your widget.

Example:

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,
        )

Hope that helped!

答案 1 :(得分:0)

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

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