Reputation: 718
I have defined a class to retrieve the device info such as the width, height, orientation, and so on.
import 'package:flutter/material.dart';
class Device {
static double? height;
static double? width;
static String? orientationType;
static String? deviceType;
void init(BuildContext context) {
final mediaQueryData = MediaQuery.of(context);
final appBar = AppBar();
final appBarHeight = appBar.preferredSize.height;
final statusBarHeight = mediaQueryData.padding.top;
final bottomBarHeight = mediaQueryData.padding.bottom;
height = mediaQueryData.size.height - appBarHeight - statusBarHeight - bottomBarHeight;
width = mediaQueryData.size.width;
orientationType = (mediaQueryData.orientation == Orientation.portrait) ? "Portrait" : "Landscape";
deviceType = (orientationType == "Portrait" && width! < 600) ? "Mobile" : "Tablet";
}
}
When I try to calculate the size then as shown below I'm getting an error.
return Container(
width: Device.width! * 0.9,
);
Error message:
Null check operator used on a null value
But when I use it without multiplying width: Device.width
it works fine and need not have to insert the null
check operator as well.
Upvotes: 0
Views: 91
Reputation: 604
Converting it to singleton class with parameters.
import 'package:flutter/material.dart';
class Device {
late double height;
late double width;
late String orientationType;
late String deviceType;
static final Device _inst = Device._internal();
Device._internal();
factory Device({BuildContext context}) {
final mediaQueryData = MediaQuery.of(context);
final appBar = AppBar();
final appBarHeight = appBar.preferredSize.height;
final statusBarHeight = mediaQueryData.padding.top;
final bottomBarHeight = mediaQueryData.padding.bottom;
_inst.height = mediaQueryData.size.height - appBarHeight - statusBarHeight - bottomBarHeight;
_inst.width = mediaQueryData.size.width;
_inst.orientationType = (mediaQueryData.orientation == Orientation.portrait) ? "Portrait" : "Landscape";
_inst.deviceType = (orientationType == "Portrait" && width! < 600) ? "Mobile" : "Tablet";
return _inst;
}
}
Use it like this:
Device(context: context).height
For more info on this topic visit:
Upvotes: 1