Reputation: 1167
I have a positioned Text element that sits on top of an Image element in a Stack. I'd like to apply a simple background color to that Text element, so that it frames the text like a caption box:
I can do this by inserting a Container as another positioned child in that Stack. But I'd have to recalculate the width every time the text string changes, which is sub-optimal. Is there a better way?
var stack = new Stack(
children: <Widget>[
new Image.asset ( // background photo
"assets/texture.jpg",
fit: ImageFit.cover,
height: 600.0,
),
new Positioned ( // headline
child: new Container(
decoration: new BoxDecoration (
backgroundColor: Colors.black
),
),
left: 0.0,
bottom: 108.0,
width: 490.0,
height: 80.0,
),
new Positioned (
child: new Text (
"Lorem ipsum dolor.",
style: new TextStyle(
color: Colors.blue[500],
fontSize: 42.0,
fontWeight: FontWeight.w900
)
),
left: 16.0,
bottom: 128.0,
)
]
);
Upvotes: 20
Views: 17812
Reputation: 259
As of Flutter 0.10.3 has changed BoxDecoration. backgroundColor: is no longer a valid property. It is now color:.
Upvotes: 7
Reputation: 1167
Just nest the Text element as a child within the Container that has the BoxDecoration (i.e. background color); the Container will stretch to fit the Text inside. Additionally, one can specify padding for that Container, which eliminates the need to hardcode a width/height for the box.
var stack = new Stack(
children: <Widget>[
new Image.asset ( // background photo
"assets/texture.jpg",
fit: ImageFit.cover,
height: 600.0,
),
new Positioned ( // headline
child: new Container(
child: new Text (
"Lorem ipsum dolor.",
style: new TextStyle(
color: Colors.blue[500],
fontSize: 42.0,
fontWeight: FontWeight.w900
)
),
decoration: new BoxDecoration (
backgroundColor: Colors.black
),
padding: new EdgeInsets.fromLTRB(16.0, 16.0, 16.0, 16.0),
),
left: 0.0,
bottom: 108.0,
),
]
);
Upvotes: 19