Menu
CoddyTech

Waiting With async and await

Part of the Data and the Network section of Coddy's Flutter journey. Lesson 2 of 27.

The tea app should say Boiling... first and Tea is ready later. With a callback inside Future.delayed, the order is hard to read. Dart has a clearer way: await.

Future<void> boil() async {
  setState(() {
    message = 'Boiling...';
  });
  await Future.delayed(const Duration(seconds: 3));
  setState(() {
    message = 'Tea is ready';
  });
}

await pauses this function until the future is done, then carries on with the next line. The code reads top to bottom, in the order things happen.

Two rules come with it. A function that uses await is marked async. An async function returns a Future: Future<void> when it gives nothing back. Only this function pauses. The rest of the app keeps running.

challenge icon

Challenge

Easy

Rewrite boil with async and await:

  • right after the tap, the message is Boiling...
  • 3 seconds later, it is Tea is ready

Try it yourself

import 'package:flutter/material.dart';

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

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

  @override
  Widget build(BuildContext context) {
    return const MaterialApp(
      debugShowCheckedModeBanner: false,
      home: TeaScreen(),
    );
  }
}

class TeaScreen extends StatefulWidget {
  const TeaScreen({super.key});

  @override
  State<TeaScreen> createState() => _TeaScreenState();
}

class _TeaScreenState extends State<TeaScreen> {
  String message = 'The water is cold';

  void boil() {
    Future.delayed(const Duration(seconds: 3), () {
      setState(() {
        message = 'Tea is ready';
      });
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: Center(
        child: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            Text(message, style: const TextStyle(fontSize: 28)),
            const SizedBox(height: 24),
            ElevatedButton(onPressed: boil, child: const Text('Boil water')),
          ],
        ),
      ),
    );
  }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Data and the Network

Practice on your own: Online Flutter compiler