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

question: why is `ScreenUtil.init` obtaining a `context` from `Navigator`? #466

Closed jenshor closed 1 year ago

jenshor commented 1 year ago

I'm working on fixing a bug within the widgetbook package. In Widgetbook, we have two navigators. One for navigating through multiple of the catalogued widgets and one navigator for previewing/rendering the selected use-case.

When previewing using a Widget that uses the flutter_screenutil package, the code 200.h returned the correct height. However, whenever the UI is refreshed (for example by calling setState()), 200.h does not longer return the correct height.

I debugged into the code of ScreenUtil.init (see this code) and realized something that I'd consider odd.

The lines

final navigatorContext = Navigator.maybeOf(context)?.context as Element?;
final mediaQueryContext =
    navigatorContext?.getElementForInheritedWidgetOfExactType<MediaQuery>();

obtain a new context.

However, based on how ScreenUtil is used, the context that is obtained might not be the one that contains the inherited MediaQuery causing 200.h to return a different value. I changed the source code of flutter_screenutil to

final mediaQueryContext =
    context?.getElementForInheritedWidgetOfExactType<MediaQuery>();

With this code, the MediaQuery of the context is the one I'm expecting.

Question:

What's the reason to first fetch the Navigator and extract another (possibly different) context from there?

github-actions[bot] commented 1 year ago

This issue is stale because it has been open for 30 days with no activity.

github-actions[bot] commented 1 year ago

This issue was closed because it has been inactive for 14 days since being marked as stale.

lizhuoyuan commented 1 year ago

hello, i'm going to rethink the context here