Flutter 中如何制作屏幕高度和宽度的全局变量?

hel*_*end 1 dart flutter

我正在尝试在变量文件中为屏幕的高度和宽度设置变量,以便我可以从所有其他文件访问它们。

这是我的代码:

import 'package:flutter/material.dart';

BuildContext context = context;

double screenWidth = MediaQuery.of(context).size.width;
double screenHeight = MediaQuery.of(context).size.height;
Run Code Online (Sandbox Code Playgroud)

然而,这会导致应用程序无法运行并返回消息

在初始化期间读取静态变量“上下文”

jam*_*lin 7

您需要一个有效的BuildContext实例,并且不能在 aWidgetbuild方法之外获得一个。您可以改为声明全局变量并稍后初始化它们:

double? screenWidth;
double? screenHeight;

class MyWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // Initialize `screenWidth` and `screenHeight` only if they haven't
    // already been set.
    screenWidth ??= MediaQuery.of(context)?.size.width;
    screenHeight ??= MediaQuery.of(context)?.size.height;

    ...
  }
}
Run Code Online (Sandbox Code Playgroud)

在您的情况下,您也可以使用Window.physicalSize

import 'dart:ui' as ui;

late double screenWidth;
late double screenHeight;

void main() {
  // Convert from physical pixels to Flutter's logical pixels.
  screenWidth = ui.window.physicalSize.width / ui.window.devicePixelRatio;
  screenHeight = ui.window.physicalSize.height / ui.window.devicePixelRatio;
  ...
}
Run Code Online (Sandbox Code Playgroud)

另请注意,在这两个示例中,屏幕大小将设置一次,因此如果屏幕方向发生变化,这些值将不会自行更新。