Examples of using Future, async, await in Flutter

Last updated on November 5, 2020 The Frog Loading... Post a comment

A few examples of using Future, async, and await in Flutter applications.

Example 1: Easy To Understand

The code:

Future<void> doSomething() {
  return Future.delayed(Duration(seconds: 2), () { print('Task completed!');});
}

void main() {
  doSomething();
  print('Doing...');
}

You’ll see Doing… before Task completed!, like this:

Example 2: Fetching Data From APIs

Fetching data from APIs on remote servers is one of the most common use cases of Future, async, await in Flutter. For convenience, you should install the http package, a Future-based library for making HTTP requests.

To install the http package, add http: ^0.12.2 to the dependencies section in your pubspec.yaml, like this:

dependencies: 
  flutter:
    sdk: flutter
  http: ^0.12.2

Then run this command:

flutter pub get

The code:

import 'package:http/http.dart' as http;
import 'dart:convert';

Future<void> _loadData() async {
    // This is an open api for testing
    // Thanks to the Typicode team
    final url = 'https://jsonplaceholder.typicode.com/todos';
    try {
      final http.Response response = await http.get(url);
      final _loadedTodos = json.decode(response.body);
      print(_loadedTodos); 
    } catch (err) {
      throw err;
    }
}

// Call the _loadData function somewhere 

You can find the complete code in this article: Implementing Pull-to-Refresh in Flutter

Hope this helps. Happy coding 🙂

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments

Related Articles