Unclear how to handle conditional UI, when resolving the condition is async
@mit-mit commented on Fri Dec 08 2017
Occasionally apps need to render different UI depending on some condition that is resolved asynchronously, for example:
-
Dependent on device vs. emulator: The
device_infopackage has anisEmulatorAPI, but this is async -
Dependent on login state: The
firebase_authpackage handles login, but asking if the user is logged in or not is async
It would be great if flutter.io has documentation for how to generally render UI that is conditional on async state.
@goderbauer commented on Fri Dec 28 2018
The cookbook would be a great place to add this (https://flutter.io/docs/cookbook).
Should this be moved to the website repo?
@brianegan, can you add this to your todo list?
@Sfshaza Happy to!
@mit-mit To help guide this, I'd love some advice! Overall, I'm trying to answer the question: What would the title of this recipe be to focus it down on the problems someone might be solving?
Depending on the needs of the developer / app, I could see the solutions going a few ways:
- "Displaying Widgets based on asynchronous data"
- "Navigating to a new screen after successful login"
- "Starting the app with a login screen if the user is logged out"
This would be backed up by the following solutions:
- Use
FutureBuilderto render the correct Widget depending on the response. - Listen to the Future and push / pop the correct routes.
- Await the Future in the
mainpart of the app to define the correcthomeroute.
What are your thoughts? Do any of these fit what you were imagining and fulfill the needs of the users you're talking to, or did ya have something a bit different in mind?
@mit-mit : This issue seems a bit long in the tooth. Is this still an ongoing concern? Do you have anything to add to this issue?
I think this is still relevant, but not 100% sure. @Hixie ?
The problem is one that is regularly faced by developers, certainly. Whether we already explain how to do it or not, I don't know. Probably. FutureBuilder is one solution. StatefulWidget and setState is another.
@miquelbeltran, please review
As with https://github.com/flutter/website/issues/2087, the use of FutureBuilder is covered in recipes like
https://docs.flutter.dev/cookbook/networking/fetch-data. There is also https://docs.flutter.dev/ui/interactivity which goes deeper on the basics of stateful UI. In more general terms, the Think Declarative section covers the theory on "how the UI can wait for async results".