首页 > 解决方案 > 如何在 MaterialApp 级别定义媒体查询,以便可以将其应用于 Flutter 中的所有屏幕/脚手架?

问题描述

在我的启用 web 的颤振应用程序中,为了添加媒体查询,我在 index.html 文件的标签中添加了css类。body

<head>
    ....
    <style>
      .mobile{
        max-width:auto;
      }
      @media (min-width: 600px) {
        .mobile{
           max-width:400px;
        }
      }
    </style>
</head>
<body class="mobile">
   <script src="main.dart.js" type="application/javascript"></script>
</body>

但是这里的颤动是在flt-glass-pane标签内创建标签body,它正在渲染 UI 溢出body标签。

在我的第二种方法中,我必须在屏幕级别添加 MediaQuery,但我不想在每个scaffold/screen.

那么有没有其他方法可以让我只MateriaApp在文件中或文件中应用媒体查询index.html一次。

标签: flutterflutter-layoutflutter-dependenciesflutter-web

解决方案


在 Material App 中使用“builder”

MaterialApp(
 ...
 ...
 builder: (context, child) {
    double screenWidth = MediaQuery.of(context).size.width;
    return Center(
             child: Container(
                      width: screenWidth > 600 ? 400 : screenWidth,
                      child: child,
                    ),
           );
      }, 
);

推荐阅读