0
0
Fluttermobile~5 mins

Async/await and Futures in Flutter

Choose your learning style9 modes available
Introduction

Async/await and Futures help your app wait for tasks that take time, like loading data, without freezing the screen.

When loading data from the internet, like fetching user info.
When reading files or databases that take time to respond.
When waiting for a timer or delay before doing something.
When calling functions that take time but you want the app to stay responsive.
Syntax
Flutter
Future<Type> functionName() async {
  // code that waits for something
  var result = await someAsyncCall();
  return result;
}

Future means a value that will be ready later.

async marks a function that can wait for Futures.

Examples
A simple async function that returns a Future with a String.
Flutter
Future<String> fetchUserName() async {
  return 'Alice';
}
This function waits 2 seconds before returning 42.
Flutter
Future<int> waitAndReturn() async {
  await Future.delayed(Duration(seconds: 2));
  return 42;
}
Shows how to wait for a Future result before printing.
Flutter
Future<void> printUserName() async {
  String name = await fetchUserName();
  print(name);
}
Sample App

This Flutter app shows a loading spinner for 2 seconds, then displays a greeting message. It uses async/await to wait for the greeting.

Flutter
import 'package:flutter/material.dart';

void main() {
  runApp(const MyApp());
}

class MyApp extends StatelessWidget {
  const MyApp({super.key});

  Future<String> fetchGreeting() async {
    await Future.delayed(const Duration(seconds: 2));
    return 'Hello from Future!';
  }

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: Scaffold(
        appBar: AppBar(title: const Text('Async/Await Example')),
        body: Center(
          child: FutureBuilder<String>(
            future: fetchGreeting(),
            builder: (context, snapshot) {
              if (snapshot.connectionState == ConnectionState.waiting) {
                return const CircularProgressIndicator();
              } else if (snapshot.hasError) {
                return const Text('Error occurred');
              } else {
                return Text(snapshot.data ?? 'No data');
              }
            },
          ),
        ),
      ),
    );
  }
}
OutputSuccess
Important Notes

Use async on functions that return a Future and use await to pause until the Future finishes.

Never block the main UI thread; async/await helps keep the app smooth and responsive.

Use FutureBuilder widget in Flutter to show UI based on Future state.

Summary

Async/await lets your app wait for slow tasks without freezing.

A Future is a value that will be ready later.

Use FutureBuilder to update UI when a Future completes.