skip to Main Content

In my Flutter project I want to initialise BLoC (Provider/Cubit) once API responds with definition of shape of the state required for entire app.

Consider following shapes

shape-1

{
  arr1: [],
  arr2: [],
  selected: false
}

shape-2

{
  arr1: [],
  obj1: {},
  selectedChoiceId: 8
}

As shown above there is no fixed shape of object in the response, hence state of application should be initialised once API responds.

I am using Flutter with BLoC configuration as per recommended by official documentation.

Please suggest how can I achieve "Dynamic state initialisation" with BloC.

2

Answers


  1. You should not initialize your state from an API that could take longer or not respond at all.

    Your first state is "Uninitialized" and you have to figure out what your app should do in that state. Maybe just show a spinner. But it has to do something. And then, when you get the data, you can switch to another state, based on the data. There is no big secret here, you can read your dynamic data and use simple if statements to figure out what kind of data it is and what your next state is, based on that.

    Login or Signup to reply.
  2. As per my understanding you want to save your dynamic data state in whole app even you are in widget tree or not. so my suggestions are use ServiceLocator Get_IT to create global object of on of your data class where you can save your dynamic data inside map (var mapData = <String, dynamic>{}) with unique key so later you can retrieve that data and manipulate

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search