我正在尝试从Flutter中的父部件传递堆栈的高度,但我无法做到。请帮助我找到解决方案,我将把我的代码作为参考。
父小工具
@override
Widget build(BuildContext context) {
return SingleChildScrollView(
child: Stack(
children: [
Picturebackground(//pass Stack height ),
Center(
child: Column(
mainAxisSize: MainAxisSize.max,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
Text('varying text'),
],
),
),
],
),
);
}
子部件
dynamic listImagesnotFound = ['assets/svg1.svg','assets/svg2.svg','assets/svg3.svg','assets/svg4.svg'];
Random rnd;
class Picturebackground extends StatelessWidget {
final double stack_height;
Picturebackground ({Key key, this.stack_height}) : super(key: key);
Widget build(BuildContext context) {
int min = 0;
int max = listImagesnotFound.length - 1;
rnd = new Random();
int r = min + rnd.nextInt(max - min);
String image_name = listImagesnotFound[r].toString();
return SvgPicture.asset(image_name,
fit: BoxFit.cover,
width: MediaQuery.of(context).size.width,
height: // get the height of the Stack
);
}
}
如何将堆栈的高度传递给SVGPicture。
可以使用LayoutBuilder
获取PictureBackground
小部件的约束:
dynamic listImagesnotFound = ['assets/svg1.svg','assets/svg2.svg','assets/svg3.svg','assets/svg4.svg'];
Random rnd;
class Picturebackground extends StatelessWidget {
Widget build(BuildContext context) {
int min = 0;
int max = listImagesnotFound.length - 1;
rnd = new Random();
int r = min + rnd.nextInt(max - min);
String image_name = listImagesnotFound[r].toString();
return LayoutBuilder(
builder: (context, constraints) {
// get here
final height = constraints.maxHeight;
return SvgPicture.asset(image_name,
fit: BoxFit.cover,
width: MediaQuery.of(context).size.width,
height: height // use here
);
}
);
}
}