How to Extract Data from a Future without Using a FutureBuilder

How to Extract Data from Future without Using FutureBuilder?

FutureBuilder calls the future function to wait for the result, and as soon as it produces the result it calls the builder function where we build the widget. So in today’s article, we will go through how to extract data from Future without using FutureBuilder.

Take your Flutter development skills to the next level as we dive into the art of extracting data from Futures without relying on the traditional FutureBuilder. In this insightful blog, we unveil alternative methods and techniques that allow you to efficiently retrieve and process data from asynchronous operations. Discover powerful concepts like async/await, the completion of Future objects, and error handling strategies to extract the desired data precisely when you need it. Whether you’re dealing with network requests, database queries, or any other asynchronous tasks, our comprehensive guide will empower you to harness the full potential of Futures, unlocking a world of possibilities for your Flutter applications. Say goodbye to the limitations of FutureBuilder and embrace a more flexible and customizable approach to data extraction.

Know How to extract data from Future without using FutureBuilder?

FutureBuilder is just a convenient helper to get the widget tree rebuilt when a Future completes. You can try with the below code snippet

funcThatReturnsFuture().then((result) {
  print(result);
  setState(() {
    someVal = result;
  })
})

or

Future funcThatMakesAsyncCall() async {
  var result = await funcThatReturnsFuture();
  print(result);  
  setState(() {
    someVal = result;
  })
}

The main limitation is that you can’t return the value directly to the caller without a Future, because there is no way to get back from async execution to sync execution

So a Future is a just semantic sugar for a callback. Now imagine you had:

void fetchName(void Function(String) callback);

void main() {
  fetchName((name) {
     print('Your name is: $name');
  });
}

One of the advantages of using FutureBuilder is it really helps make sense of asynchronous abstractions like Future and StreamBuilder for Stream, and let you focus on writing synchronous builder code:

new FutureBuilder<String>(
  future: _calculation, // a Future<String> or null
  builder: (BuildContext context, AsyncSnapshot<String> snapshot) {
    switch (snapshot.connectionState) {
      case ConnectionState.none: return new Text('Press button to start');
      case ConnectionState.waiting: return new Text('Awaiting result...');
      default:
        if (snapshot.hasError)
          return new Text('Error: ${snapshot.error}');
        else
          return new Text('Result: ${snapshot.data}');
    }
  },
)

The only way to be able to consume a Future without creating a Widget object is by using the Future API.

The Future API allows the parsing of a Future object as though it was an AsyncSnapshot object which is where one would parse .data in a FutureBuilder builder: function.

This can be performed on a returned Future object which can use async with await. For example:

Future regionName = dbClient.getRegionNameFromZipCode(int.parse(zipCode)); <-- this database method getRegionNameFromZipCode returns a Future object and uses async and await

regionName.then((data) {
   String hZonesString = data[0]['hzone'];
   print(hZonesString);
}, onError: (e) {
     print(e);
   });

Conclusion:

Thanks for Reading !!! Lots of informative content coming up your way!!! Stay Connected

So in this article, we have been through how to extract data from Future without using FutureBuilder.

Keep Learning !!! Keep Fluttering !!!

Do let us know if you are still facing problems

FlutterAgency.com is our portal Platform dedicated to Flutter Technology and Flutter Developers. The portal is full of cool resources from Flutter like Flutter Widget GuideFlutter ProjectsCode libs and etc.

FlutterAgency.com is one of the most popular online portals dedicated to Flutter Technology and daily thousands of unique visitors come to this portal to enhance their knowledge of Flutter.

Abhishek Dhanani

Written by Abhishek Dhanani

Abhishek Dhanani, a skilled software developer with 3+ years of experience, masters Dart, JavaScript, TypeScript, and frameworks like Flutter and NodeJS. Proficient in MySQL, Firebase, and cloud platforms AWS and GCP, he delivers innovative digital solutions.

1 comment

  1. I don’t get how you cant show us what is dbClient.getRegionNameFromZipCode ? its kinda pivotal

Leave a comment

Your email address will not be published. Required fields are marked *


Discuss Your Project

Connect with Flutter Agency's proficient skilled team for your app development projects across different technologies. We'd love to hear from you! Fill out the form below to discuss your project.

Have Project For Us

Get in Touch

"*" indicates required fields

ready to get started?

Fill out the form below and we will be in touch soon!

"*" indicates required fields