How to use Future API in Flutter with code example

In my last flutter example code, we explore how to use Flutter Async and Await for asynchronous operation in Flutter.

Apart from flutter async and await, we can also use Future API to accomplish asynchronous operation in flutter.

Future object is what is return in async operation in Flutter. When an async method is called.

A partial completed Future object is return while in await state. When the method return, the Future object returned can contain either a value or an error.

Let’s go ahead and show a simple flutter project that highlights how to use Future API for async operation in Flutter.

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.

main.dart

import 'package:flutter/material.dart';
import 'future_api.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 future_api.dart.

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

import 'dart:async';

import 'package:flutter/material.dart';

class FutureInFlutter extends StatefulWidget {
  @override
  _FutureInFlutterState createState() => _FutureInFlutterState();
}

class _FutureInFlutterState extends State<FutureInFlutter> {
  bool _isLoading = false;

  initApp() async {
    setState(() => _isLoading = true);
    Future.delayed(Duration(seconds: 6)).then((_) {
      setState(() => _isLoading = false);
    });
  }

  @override
  void initState() {
    super.initState();
    initApp();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(title: Text("Future Example")),
      body: Center(
          child: _isLoading
              ? CircularProgressIndicator()
              : Text("Future Completed!",
                  style: TextStyle(fontSize: 20, fontWeight: FontWeight.bold))),
    );
  }
}

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