Home > Software engineering >  Where to provide Future value
Where to provide Future value

Time:10-06

maybe someone can help me with the following:

I have Bloc that provides a single state and I have a simple widget tree.

Down in my widget tree I need an information to display. It is the device name of the used device. I can access this information via the device_info_plus plugin. The returned type from the plugin is a Future.

What would be the best way to provide the device name to my build() function down in the widget tree.

Right now different solutions come to my mind:

  1. Access the device name in the bloc and emit it within the state (which would work because there is only on state I am listening to, but I don't like this solution.

  2. Access the device name in the bloc and provide it via a getter.

  3. Change my widget which is stateless at the moment to a stateful one and return a Futurebuilder. The problem here I see is that a Futurebuilder is designed for stuff like queries and not for a simple string I receive from the Plugin. I think this would work but futurebuilder is not used in the right way.

  4. My preferred solution is to access the device name at the point it is actually used, which is my stateless widget. Unfortunately I can't await a Future in the build method and no proper solution comes to my mind how to solve this.

I would appreciate if someone can provide me a good solution on how to tackle this.

Thank you in advance.

CodePudding user response:

You have 2 options.

  1. Preload the future somewhere and have the variable ready to show when needed. You can use any state management u like.
  2. Start fetching future excatly at the time you need it and show loading indicator until it's ready - FutureBuilder is designed for cases like this.

U don't need to await future. Await is needed to wait for any function to be done before it goes further. U don't need to wait for the future to be resolved. U can hardcore widget layout and it will be changed after setState fires. U can implement your future in initState() and set state in Future .then method.

I don't understand the use of state management like bloc when u have only one state to show.

  • Related