LoginSignup
1
1

contextを使わないでデバイスサイズを取得したい

Posted at

デバイスサイズを取得する方法

備忘録
他にいい方法があったらコメント欄で教えてください

context使用

Size size = MediaQuery.of(context).size;
double width = size.width;
double height = size.height;

contextを使わない方法

contextを使わないでデバイスサイズを取得する場合WidgetsBinding.instance.platformDispatcher.views.first.physicalSizeを用いるのですが、取得できるのは物理ピクセルでのサイズになります。
contextを用いる方法のMediaQuery.of(context).sizeで取得できるサイズは論理ピクセルです。
そのため、contextを用いずに論理ピクセルを取得したい場合はWidgetsBinding.instance.platformDispatcher.views.first.devicePixelRatioで割ってあげる必要があります

double pixelRatio = WidgetsBinding.instance.platformDispatcher.views.first.devicePixelRatio;

// 物理ピクセル
Size physicalSize = WidgetsBinding.instance.platformDispatcher.views.first.physicalSize;
double physicalSizeWidth = size.width;
double physicalSizeHeight = size.height;

// 論理ピクセル
Size logicalSize = WidgetsBinding.instance.platformDispatcher.views.first.physicalSize / pixelRatio;
double logicalSizeWidth = size.width;
double logicalSizeHeight = size.height;
1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1