Menu
CoddyTech

A Value That Arrives Later

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

Until now, everything in your apps happened at once: tap a button, the screen changes. Real apps often wait. They wait for a server to answer, for a file to load, for a timer to run out.

Dart calls a value that is not there yet a Future. The simplest one is Future.delayed: it waits for a Duration, then runs the function you give it.

Future.delayed(const Duration(seconds: 2), () {
  setState(() {
    message = 'Done';
  });
});

Your app does not freeze while it waits. The screen keeps drawing and the buttons keep working. When the 2 seconds are up, Dart runs the function, and setState redraws the screen with the new message.

challenge icon

Challenge

Easy

Tapping Boil water shows Tea is ready at once. Water takes time. Make the message change 3 seconds after the tap, with Future.delayed.

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() {
    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