What is the impact of the lazy flag in BlocProvider?
Asked Answered
R

2

5

I am trying to understand what impact does the lazy flag have. And what are the considerations for setting it as true or false?

Resilient answered 9/2, 2021 at 18:2 Comment(0)
N
11

When it is true, the Bloc or Cubit should be created lazily, that means, it is not created by the provider until the first request of accessing the Bloc such as context.read<MyBloc>

You can set lazy true when initializing is costly, or it has some side effects, i.e a Restful API called (it is not needed to call the API until user do some action and lazily created the Bloc) on otherside you can set lazy as false for prefetching data

Nepotism answered 9/2, 2021 at 18:12 Comment(2)
lazy is true by default.Chemarin
Thanks, I read some more online, and lazy seems to define the behavior of how our code works. Lazy loading means creating something only once it is needed (hence the term lazy), whereas the opposite would be to have things ready at the start itself. This may sound very obvious to those who are experienced but it wasn't so obvious for a newbie like me. Which one to use depends on the kind of loading you want your application to perform - slow at the start and then smooth or faster initial load followed by slow updates.Resilient
C
5

As the docs say:

By default, Create is called only when the instance is accessed. To override this behavior, set lazy to false.

Therefore, the impact is when Create will be called, and thus when (if at all) your your BLoC is created. By default, lazy is true, so if you never access the instance of the BLoC, it will not be created. Conversely, when lazy is false, the Create method will be called instantly when the Widget is built.

Behind the scenes, the value is passed to the underlying InheritedProvider.

Chemarin answered 9/2, 2021 at 18:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.