title: Flutter: Best Practices of Calling Async Code from UI
body: <p>I am developing a Flutter app but wondering what should I do when calling async code from UI - let's say the build method of a UI widget.</p>
  
  <p>For example, my app connects Firebase through a service class, which uses Async-Await style to grab records from Firebase. Using await ensures my service class's method will complete records retrieval before returning to the UI side.</p>
  
  <p>However, since the service class's method is marked as async, it returns a Future immediately to the calling UI widget and the UI code keeps running, before the service class's method is completed. </p>
  
  <p>Yes I can write codes for the "then()" callback to handle the retrieved records, but what about other codes inside the widget that follow, and depend on the result of the async call? Does it mean I need to embed everything inside the "then()" clause and avoid adding any execution steps after a method call that returns a Future? Any suggested pattern for such usage model?</p>
  
  <pre><code>@override
  Widget build(BuildContext context) {
  
     RealtimeDatabase.getData()  // my service class
        .then((onValue) {
          ..... // do something after the async call is completed
     }
  
     ..... // do something immediately before the async call is done
  
  
  class RealtimeDatabase {
  
      Future&lt;String&gt; getData() async {
  
      DataSnapshot dataSnapshot = await FirebaseDatabase.instance.reference().orderByKey().once(); // will wait until completed
      .....
      .....
  </code></pre>
  
  <p>Sorry if my description here is lack of clarity, any advice is much welcome.</p>
  
  <p>Jimmy</p>