Don't Use BuildContexts Cross Async Gaps Flutter BLoC Context

Created At: 2023-05-10 07:23:18 Updated At: 2023-05-10 07:36:01

If you use Flutter BLoC for state management, you may need to pass the BLoC arround, I mean you need to pass the related Context around many screen or pages, since you want to access or modify data.

Let's see the below example

Don’t use BuildContexts across async gaps

You must see that there's a yellow wiggly line. If you hover over on it, you will find the below warning

Don’t use BuildContexts across async gaps

Well, it's asking you not to use BuildContexts in a situation, it's a called during async operation. Flutter sdk gives you warning, that's because that certain context, we are trying to access, might not be available if that child is removed from the tree. 

Or if the child does not have direct relationship with the context, then if you try access the context, you might crash or other expected issues.

Like in our case, we are using the context from a controller. In this controller we don't have a Stateful class or BlocBuilder widget.

In that case, it's dangerous to access the context. To get rid of this problem, you need to use

context.mounted proptery.

You see that, we wrapped our code around context.mounted condition. It will check if the certain context is still valid or not.

 

Comment

Add Reviews