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

Rid*_*Sun 2 android flutter

我创建了一个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)));
}
Run Code Online (Sandbox Code Playgroud)

Joe*_*e B 20

如果你想使用Colors.grey(而不是使用它的 RGB 等价物 via Colors.fromRGBO),

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


Hem*_*Raj 6

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

例:

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,
        )
Run Code Online (Sandbox Code Playgroud)

希望能有所帮助!