监听window的尺寸变化,当不为空时,再runApp;runApp必须先WidgetsFlutterBinding.ensureInitialized(),确保有WidgetsFlutterBinding实例,不然会黑屏
Before Fixing:
void main() {
runApp(const MyApp());
}
使用window需导入 dart:ui
import 'dart:ui';
Please change it to the Following:
If your environment sdk: '>=2.x <3.0.0' you can use the following code:
import 'dart:ui';
Future<void> main() async {
if (window.physicalSize.isEmpty) {
window.onMetricsChanged = () {
if (!window.physicalSize.isEmpty) {
window.onMetricsChanged = null;
runApp(const MyApp());
}
};
} else {
runApp(const MyApp());
}
}
If your environment sdk: ^3.0.0 can use the following code:
Future<void> main() async {
FlutterView? flutterView = PlatformDispatcher.instance.views.firstOrNull;
if (flutterView == null || flutterView.physicalSize.isEmpty) {
PlatformDispatcher.instance.onMetricsChanged = () {
flutterView = PlatformDispatcher.instance.views.firstOrNull;
if (flutterView != null && !flutterView!.physicalSize.isEmpty) {
PlatformDispatcher.instance.onMetricsChanged = null;
runApp(const MyApp());
}
};
} else {
runApp(const MyApp());
}
}