FutureBuilder, async, await in Flutter, practical example

- Andrés Cruz

En español

Today we are going to discuss a misunderstood widget such as FutureBuilder; which at first glance may seem abstract and difficult to use, but it has a very particular use that can help us successfully complete a development that involves an asynchronous process with which, in the end, we want to draw a widget.

Demonstratively, the asynchronous process, or what is the same, that function that returns a Future, which in practice is a function that performs at least one asynchronous process, what it does is connect to the Internet through a URL and obtain data:

static Future<List<dynamic>> getComments(int classId) async {
   var url = Uri.https(baseUrlAPI, "<URL>");

   try {
     final response = await http.get(url);
     if (response.statusCode == 200) {
        return jsonMap['comments']);
     }
   } on Exception {}
   return [];
 }

Now, the future is as easy to use as indicating in the future parameter, the asynchronous method created previously, then, in the builder parameter, which is a callback, is where we build the widget that needs the input data provided by the future ; In our example, it is the list of data:

Widget _listComments() {

   return FutureBuilder(
     future: AcademyHelper.getComments(5),
     builder: (_, snapshot) {

       if (snapshot.hasData && snapshot.data != null) {
         return ListView.builder(
             shrinkWrap: true,
             itemCount: snapshot.data?.length, // comments
             itemBuilder: (_, int position) =>
                 Text(snapshot.data?[position]['comment']));
       } else {
         return const CircularProgressIndicator();
       }
     },
   );
 }

As you can see, we do not have the data returned directly, if not, we have an object called snapshot, which is nothing more than a wrapper for our data; the reason for this is because this object gives us the status of the request, since, being an asynchronous process, we will want to draw a widget BEFORE loading the data, which is then replaced by the widget built from the data.

The snapshot has parameters like hasData that specify whether the future has already been resolved; It is very important that from the future an exception does NOT occur since the future would never be resolved.

Conclusion

In the end, the FutureBuilder is particularly useful when we cannot use an asynchronous process directly in the widget tree, and we cannot do a setState to redraw the widget, since the FutureBuilder is automatically rebuilt when obtaining the data; It is as if it were an automated statefulwidget that is built automatically when obtaining the data.

Andrés Cruz

Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter

Andrés Cruz In Udemy

I agree to receive announcements of interest about this Blog.