async/await | Flutter

Tony Trejo
2 min readMar 15, 2023
async/await | Flutter

async/await

  • async defines a function that returns a Future, while await waits for a Future to complete before continuing with code execution.
  • The exceptions can be handled with try-catch when using await to handle any exceptions thrown by the Future.
  • await should always be used inside an async function.
  • Flutter provides utilities to work with asynchronous code, such as FutureBuilder and StreamBuilder.
import 'package:http/http.dart' as http;
import 'package:json_annotation/json_annotation.dart';
import 'dart:convert';

const url = 'https://jsonplaceholder.typicode.com/posts';

// Defines the data type for a single post.
class Post {

final int userId;
final int id;
final String title;
final String body;

Post({required this.userId,
required this.id,
required this.title,
required this.body});

factory Post.fromJson(Map<String, dynamic> json) {
return Post(
userId: json['userId'],
id: json['id'],
title: json['title'],
body: json['body'],
);
}
}

// Fetch posts.
Future<List<Post>> fetchPosts() async {
final response = await http.get(Uri.parse(url));
final jsonData = json.decode(response.body) as List<dynamic>;
final posts = jsonData.map((e) => Post.fromJson(e)).toList();
return posts;
}

// Request posts.
void requestPosts() async {
List<Post> posts = await fetchPosts();
print("Posts count: ${posts.length}");
}

void main() {
requestPosts(); // Output: Posts count: 100
}

Looking for a mobile development channel that’s as fun as it is informative? You’ve come to the right place! My channel is all about providing you with engaging content that will keep you coming back for more. Whether you’re interested in Flutter, iOS, Android, design or coding, I’ve got you covered. So why not join my community of fellow mobile enthusiasts and let’s explore the world of mobile together? Hit that follow button and let’s get started!

--

--