LateInitializationError:字段“screenWidth”尚未初始化。颤振异常

Aly*_*ier 1 exception dart visual-studio-code flutter

我是 flutter 的新手\n我有这个大小的配置文件,我在一个旧项目中使用了它\n现在我再次将它带到另一个项目中,它没有显示任何错误,但当我运行时它给了我一个异常:\n\xe2 \x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90 小部件捕获的异常库 \xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\ xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\ x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\ x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\xe2\x95\x90\ xe2\x95\x90\xe2\x95\x90\n构建主体(脏)时抛出以下 LateError:\nLateInitializationError:字段“screenWidth”尚未初始化。

\n
import 'package:flutter/material.dart';\n\n\nclass SizeConfig {\n  static late MediaQueryData _mediaQueryData;\n  static late double screenWidth;\n  static late double screenHeight;\n  static double? defaultSize;\n  static Orientation? orientation;\n  void init(BuildContext context) {\n    _mediaQueryData = MediaQuery.of(context);\n    screenWidth = _mediaQueryData.size.width;\n    screenHeight = _mediaQueryData.size.height;\n    orientation = _mediaQueryData.orientation;\n  }\n}\n// Get the proportionate height as per screen size\ndouble getProportionateScreenHeight(double inputHeight) {\n  double screenHeight = SizeConfig.screenHeight;\n  // 812 is the layout height that designer use\n  return (inputHeight / 812.0) * screenHeight;\n}\n// Get the proportionate height as per screen size\ndouble getProportionateScreenWidth(double inputWidth) {\n  double screenWidth = SizeConfig.screenWidth;\n  // 375 is the layout width that designer use\n  return (inputWidth / 375.0) * screenWidth;\n}\n
Run Code Online (Sandbox Code Playgroud)\n

小智 6

确保在构建方法中调用方法 init()

Widget build(BuildContext context) {
SizeConfig().init(context);}
Run Code Online (Sandbox Code Playgroud)

并确保从正确的来源导入 sizeconfig 类,例如:

导入'包:to_app/ui/size_config.dart';

你想在哪里使用它