Flutter: Is There a way to identify if the context has the required provider or if context has MediaQuery

Issue

I have situation where i am using .of(context) in a function to get the Scoped Object data and use it. However this function is sometimes invoked with a context that does not provide the required context and so it cannot be used and takes default value.

What i am trying to do is to check if the given say MediaQuery is scoped in the context and do something else rather than use default value.

Solution

we can find the widget or data is in the ancestor of the context by using this method.

context.findAncestorWidgetOfExactType<T>() != null 

for example to check if Media Query Data is in the passed context
context.findAncestorWidgetOfExactType<MediaQuery>() != null

If this check returns true then we have MediaQueryData available in the context passed.

Answered By – gamer_rk

Answer Checked By – Terry (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.