2

I want to declare a static variable and initialize it in the following function, but get the error: "The non-nullable variable 'screenWidth' must be initialized."

Code:

import 'package:flutter/material.dart';

class SizeConfig {
  static MediaQueryData _mediaQueryData;
  static double screenWidth;
  static double screenHeight;
  static double defaultSize;
  static Orientation orientation;

  void init(BuildContext context) {
    _mediaQueryData = MediaQuery.of(context);
    screenWidth = _mediaQueryData.size.width;
    screenHeight = _mediaQueryData.size.height;
    orientation = _mediaQueryData.orientation;
  }
}

3 Answers3

3

Use either late keyword or use ? after declaring the datatype of the variable so that flutter knows that you are gonna later initialise the variable at some point of time or the variable will be null .

Example:

late int variable; //the variable will be initialised later

OR

int? variable; // the variable can either have a value or can be null.

Arijeet
  • 935
  • 5
  • 19
2

You can use late keyword as you are in null safety and you want to initialize the fields latter on.

By declaring a non-nullable late variable, we promise that it will be non-null at runtime, and Dart helps us with some compile-time guarantees.

But I recommend to only use late sparingly, and to always initialize late variables when they are declared.


import 'package:flutter/material.dart';

class SizeConfig {
  static late MediaQueryData _mediaQueryData;
  static late double screenWidth;
  static late double screenHeight;
  static late double defaultSize;
  static late Orientation orientation;

  void init(BuildContext context) {
    _mediaQueryData = MediaQuery.of(context);
    screenWidth = _mediaQueryData.size.width;
    screenHeight = _mediaQueryData.size.height;
    orientation = _mediaQueryData.orientation;
  }
}

And here another thing is if you want to make your fields nullable then you cam make theme nullable by using ? after the type like bellow.


import 'package:flutter/material.dart';

class SizeConfig {
  static MediaQueryData? _mediaQueryData;
  static double? screenWidth;
  static double? screenHeight;
  static double? defaultSize;
  static Orientation? orientation;

  void init(BuildContext context) {
    _mediaQueryData = MediaQuery.of(context);
    screenWidth = _mediaQueryData?.size.width;
    screenHeight = _mediaQueryData?.size.height;
    orientation = _mediaQueryData?.orientation;
  }
}

Saiful Islam
  • 1,151
  • 13
  • 22
0

you have to add "late" keyword to your variables

Nik Evi
  • 62
  • 5