20.4 C
New York
Saturday, April 1, 2023

Examples of using Future, async, await in Flutter

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

Example 1: Easy To Understand

The code:Advertisements

import 'package:flutter/foundation.dart';

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

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

When look at your terminal window, 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 and its version to the dependencies section in your pubspec.yaml by executing this:

dart pub add http

Advertisements

Then run this command:

flutter pub get

The code:

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

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

// Call the _loadData function somewhere
void main() {
  _loadData();
}

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

Hope this helps. Further reading:

Advertisements

You can also check out our Flutter category page or Dart category page for the latest tutorials and examples.

Related Articles

Latest Articles