图片无法覆盖设备的整个尺寸,

问题描述

我正在尝试添加一个覆盖设备宽度和高度的图像,该图像还需要在其上加上文字。刚开始添加图像时,我在Image.dart文件上使用了fit: BoxFit.fill,以便图像覆盖整个屏幕并且可以正常工作。然后,为了使文本覆盖图像,我添加了将图像和文本包裹起来的Stack小部件,这样做之后,文本覆盖了图像,但是现在图像没有覆盖整个屏幕高度。为什么会发生此问题?

// main.dart
void main() {
  runApp(MaterialApp(home: MyApp()));
}

class MyApp extends StatelessWidget {
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: Colors.white,body: ImageContainer(),);
  }
}

// ImageContainer.dart
class ImageContainer extends StatelessWidget {
  Widget build(BuildContext context) {
    return Container(
      child: Column(
        mainAxisAlignment: MainAxisAlignment.center,children: [
          Stack(
            children: [
              MainImage("assets/images/startwars.jpg"),Positioned(
                bottom: 0,left: 0,child: Container(
                  child: Text(
                    "someText",style: TextStyle(fontSize: 18,fontWeight: FontWeight.bold,color: Colors.white),)
                ),)
            ],)
        ],),);
  }
}

// Image.dart
class MainImage extends StatelessWidget {
  final String _assetPath;
  MainImage(this._assetPath);
  
  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: Boxdecoration(color: Colors.red,child: Expanded(
        child: Image.asset(
          _assetPath,fit: BoxFit.fill,);
  }
}

As you can see on this image,the picture is not filling the complete height of the screen

如果您有任何疑问,请在评论中让我知道;)

解决方法

我通过向Image.dart文件中的容器添加约束来解决此问题,我所做的就是添加此行。经过大量调查后,我意识到将MediaQuery添加到高度可以告诉应用覆盖屏幕的高度,这也可以通过宽度来完成。

Widget build(BuildContext context) {
    return Container(
      decoration: BoxDecoration(color: Colors.red,),constraints: BoxConstraints.expand(height: MediaQuery.of(context).size.height),// add this line

      child: Expanded(
        child: Image.asset(
          _assetPath,fit: BoxFit.fill,);
  }
,

设置Stack的适合范围以扩展:

Stack(
  fit: StackFit.expand,children: [],);
,

您可以设置Stack fit .. 堆叠 适合:StackFit.expand,...) 还可以添加Container(child:Image(...),width:double.infinity,heigh:...)