即使使用Mediaquery.of(context),跨设备的窗口小部件大小也不一致

问题描述 投票:0回答:1

我的应用解析度有问题。根据我使用的设备,我在Pageview和GridList上使用的卡的大小不同。无论设备的类型和大小如何,我都希望它们相同。

我正在使用

Mediaquery.of<context).size 
Mediaquery.of<context).devicePixelRatio

获取设备的高度,宽度和像素比。

这些是与我使用的设备相关的打印件:

Emulator (Pixel 3a):
I/flutter (11909): height: 759.2727272727273
I/flutter (11909): width: 392.72727272727275
I/flutter (11909): pixel ratio: 2.75

My phone (Galaxy S9):
I/flutter ( 8712): height: 692.0
I/flutter ( 8712): width: 360.0
I/flutter ( 8712): pixel ratio: 3.0

我在S9上的屏幕分辨率实际上是FHD + 2220x1080,与Pixel 3a的分辨率相同。我不知道为什么它显示的分辨率这么低,为什么它们也不同!那没有道理。

这是我的代码:(全部在CustomScrollView中)

SliverToBoxAdapter(
  child: Padding(
    padding: const EdgeInsets.all(20.0),
    child: Text(
      I18n.of(context).bestSelling,
      style: kHeaderTextStyle,
    ),
  ),
),
SliverToBoxAdapter(
  child: Container(
    height: screenSize.height / 3.5,
    child: PageView.builder(
      controller: PageController(
        initialPage: 1,
        viewportFraction: 0.14*screenRatio,
      ),
      scrollDirection: Axis.horizontal,
      itemCount: bestProducts.length,
      itemBuilder: (context, index) {
        return ProductCardBS(bestProducts[index]);
      },
    ),
  ),
),
SliverToBoxAdapter(
  child: Padding(
    padding: const EdgeInsets.all(20.0),
    child: Text(
      I18n.of(context).sales,
      style: kHeaderTextStyle,
    ),
  ),
),
SliverPadding(
  padding: const EdgeInsets.only(
    left: 24,
    right: 24,
    bottom: 8.0,
  ),
  sliver: SliverGrid(
    delegate: SliverChildBuilderDelegate(
      (_, index) {
        return ProductCard(saleProducts[index]);
      },
      childCount: saleProducts.length,
    ),
    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
      crossAxisCount: 2,
      mainAxisSpacing: 6.0,
      crossAxisSpacing: 6.0,
      childAspectRatio: 0.215 * screenRatio,
    ),
  ),
),

我还试图将screenRatio更改为screenSize.height,但是我两种方式都得到了不同的尺寸。

这些是与代码相关的图片,第一个来自我的S9,第二个来自Pixel 3a:

[enter image description here enter image description here

注意卡片上的高度不同。

flutter flutter-layout
1个回答
1
投票

MediaQuary没有提供您的物理像素数。这就是为什么您的屏幕具有2220x1080像素,但是会说少一些的原因。

如果您想要确切的像素数,可以使用window中的dart:ui单例。

var screenSize = window.physicalSize;

并使用SizedBox小部件将小部件强制为精确大小。

此外,您也应禁止将viewportFraction与任何东西相乘。它已经是屏幕的百分比。

viewportFraction: 0.14*screenRatio, -> viewportFraction: 0.14,

还有一个名为FractionallySizedBox的小部件,其总是占据屏幕的相同部分:

FractionallySizedBox(
      heightFactor: 0.2,
      widthFactor: 0.28,
      child: ...,
    ),
© www.soinside.com 2019 - 2024. All rights reserved.