ensureScreenSize static method

Future<void> ensureScreenSize([
  1. FlutterView? window,
  2. Duration duration = const Duration(milliseconds: 10)
])

Manually wait for window size to be initialized

Recommended to use before you need access window size or in custom splash/bootstrap screen FutureBuilder

example:

...
ScreenUtil.init(context, ...);
...
  FutureBuilder(
    future: Future.wait([..., ensureScreenSize(), ...]),
    builder: (context, snapshot) {
      if (snapshot.hasData) return const HomeScreen();
      return Material(
        child: LayoutBuilder(
          ...
        ),
      );
    },
  )

Implementation

static Future<void> ensureScreenSize([
  ui.FlutterView? window,
  Duration duration = const Duration(milliseconds: 10),
]) async {
  final binding = WidgetsFlutterBinding.ensureInitialized();
  binding.deferFirstFrame();

  await Future.doWhile(() {
    if (window == null) {
      window = binding.platformDispatcher.implicitView;
    }

    if (window == null || window!.physicalSize.isEmpty) {
      return Future.delayed(duration, () => true);
    }

    return false;
  });

  binding.allowFirstFrame();
}