OpenFlutter / flutter_screenutil

Flutter screen adaptation, font adaptation, get screen information
https://pub.dartlang.org/packages/flutter_screenutil
Apache License 2.0
3.87k stars 493 forks source link

with DevicePreview and useInheritedMediaQuery: true, throw an exception #434

Closed nEdAy closed 1 year ago

nEdAy commented 1 year ago

Whenever I turn off DevicePreview, I throw an exception:

dependOnInheritedWidgetOfExactType() or dependOnInheritedElement() was called before _ScreenUtilInitState.initState() completed. When an inherited widget changes, for example if the value of Theme.of() changes, its dependent widgets are rebuilt. If the dependent widget's reference to the inherited widget is in a constructor or an initState() method, then the rebuilt dependent widget will not reflect the changes in the inherited widget. Typically references to inherited widgets should occur in widget build() methods. Alternatively, initialization based on inherited widgets can be placed in the didChangeDependencies method, which is called after initState and whenever the dependencies change thereafter.

runApp(
        DevicePreview(
            enabled: !kReleaseMode,
            builder: (context) => const MyApp())
class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final botToastBuilder = BotToastInit();
    return ScreenUtilInit(
      designSize: const Size(375, 812),
      minTextAdapt: true,
      splitScreenMode: true,
      **useInheritedMediaQuery: true,**
      builder: (BuildContext context, Widget? child) {
        return RefreshConfiguration(
          child: GetMaterialApp(
            **useInheritedMediaQuery: true,**
            builder: (context, child) {
              child = botToastBuilder(context, child);
              child = DeveloperWidget(child: child);
              **child = DevicePreview.appBuilder(context, child);**
              return child;
            },
          ),
        );
      },
    );
  }
}
  @override
  void initState() {
    super.initState();
    mediaQueryData = newData;
    binding.addObserver(this);
  }

screenutil_init.dart ↓

  MediaQueryData get newData {
    if (widget.useInheritedMediaQuery) {
      final data = MediaQuery.maybeOf(context);

      if (data != null) {
        wrappedInMediaQuery = true;
        return data;
      }
    }

    return MediaQueryData.fromWindow(binding.window);
  }

I tried to change the code at initState and the problem was solved, but I'm not sure if it was the right change.

  @override
  void initState() {
    super.initState();
    mediaQueryData = MediaQueryData.fromWindow(binding.window);
    binding.addObserver(this);
  }
lizhuoyuan commented 1 year ago

try 5.6.0