Flutter avoid multiple bloc creation

Issue

I use MaterialApp.router.
the build function of MainRouterDelegate is called 4 times.
Every time it’s called, a screen and its bloc are created.
In the bloc, I make HTTP calls. I don’t want to make the same calls every time the bloc is created.
How can I avoid that?

Solution

Several options:

  1. If there is only one instance of the bloc in the whole app, you can add a BlocProvoder above MaterialApp and the bloc will be available anywhere in the app, for any route.

  2. If there are blocs for specific elements identified by some unique id that you need to create on the fly, but you want to make sure you only create once, you can use essentially a main bloc or just getIt to keep track of a map of IDs to blocs that have already been instantiated. When you need to provide a bloc in a build function that might be called repeatedly, just check first if you already have a copy of the bloc you are trying to provide in your bloc-map. If not, create one and save it with the element’s ID.

Answered By – Kris

Answer Checked By – Pedro (FlutterFixes Volunteer)

Leave a Reply

Your email address will not be published.