How to use Async and Await in Flutter with code example

Flutter is a single threaded mobile SDK. In single thread application, every code execution happens in the main thread naturally.

This can cause an issues when executing code that takes long time to finish.

It implies that other subsequent executions will be place on hold until the long running task completes.

In other to avoid blocking the main thread while long running task is being executed, flutter supports asynchronous operation.

One way to achieve asynchronous operation in flutter is with Async and Wait API.

An async function is one that has the async keyword before its body. The await keyword works only in async functions.

Now that the concept is clear lets explore a simple example with source code.

Create new Flutter Project

In your Visual Studio Code, go to View menu > Command Palette.

In the open dialog, select Flutter. Enter the name of your Flutter project and hit enter key button.

In the lib folder, open the main.dart file and add the code below.

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

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        // This is the theme of your application.
        //
        // Try running your application with "flutter run". You'll see the
        // application has a blue toolbar. Then, without quitting the app, try
        // changing the primarySwatch below to Colors.green and then invoke
        // "hot reload" (press "r" in the console where you ran "flutter run",
        // or simply save your changes to "hot reload" in a Flutter IDE).
        // Notice that the counter didn't reset back to zero; the application
        // is not restarted.
        primarySwatch: Colors.blue,
      ),
      home: AsyncAwait(),
    );
  }
}

Create new Dart file in lib folder

Go to the lib folder and create a dart file. Name the file asyncawait.dart.

Open the newly created dart file and add the code below.

import 'dart:async';

import 'package:flutter/material.dart';

class AsyncAwait extends StatefulWidget {
  @override
  _AsyncAwaitState createState() => _AsyncAwaitState();
}

class _AsyncAwaitState extends State<AsyncAwait> {
  bool _isLoading = false;

  void _asyncAction() async {
    setState(() => _isLoading = true);

    await Future.delayed(Duration(seconds: 5));

    setState(() => _isLoading = false);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Async and Await example")),
      body: Center(
        child: _isLoading
            ? CircularProgressIndicator()
            : RaisedButton(
                child: Text("Start Asyncronous action"),
                color: Colors.red,
                onPressed: _asyncAction,
              ),
      ),
    );
  }
}

As you can see, we have imported the dart:async.

We have create a method with async keyword before the method body and await inside the method like below code.

void _asyncAction() async {
    setState(() => _isLoading = true);

    await Future.delayed(Duration(seconds: 5));

    setState(() => _isLoading = false);
  }

RUN YOUR APP

You can use flutter command to run your app – $ flutter run

If everything goes well, you will see screen similar to the image below in your flutter device.

If you have any question or suggestions kindly use the comment box or you can contact us directly through our contact page below.

Add a Comment