Open In App

Flutter – Handle Future Methods Using Future.then() Method

Last Updated : 06 Nov, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Handling the Future methods is am important part ,In Flutter, we can use the Future.then() method to perform an action when a Future completes its execution. In this we are going to create an button by clicking the button a Future Method will start executing for 4 seconds then after the execution the Result will be displayed by the help of Future.then() Method. A sample video is given below to get an idea about what we are going to do in this article.

Basic Example or Syntax of Future.then() Method

Future<int> fetchData() async {
await Future.delayed(Duration(seconds: 2));
return 42;
}
void main() {
fetchData().then((int result) {
print("Data received: $result");
});
}

Step By Step Implementation

Step 1: Create a New Project in Android Studio

To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.

Step 2: Import the Package

First of all import material.dart file.

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

Step 3: Execute the main Method

Here the execution of our app starts.

Dart




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


Step 4: Create MyApp Class

In this class we are going to implement the MaterialApp, here we are also set the Theme of our App.

Dart




class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
       debugShowCheckedModeBanner: false,
       theme: ThemeData(
        // Set the app's primary theme color
        primarySwatch: Colors.green, 
      ),
      home: MyHomePage(),
    );
  }
}


Step 5: Create MyHomePage Class

In this class we are going to define an Future method which will execute for 4 seconds. Then we display the Result of the future method Using Future.then() method. Comments are added for better understanding. and we created a button by pressing the future method will start its execution for 4 seconds.

Future Method:

// Act as a Future Method that will fetches data from an API.
Future<String> fetchData() async {
// Simulate the time take by API request delay
await Future.delayed(Duration(seconds: 4));
return 'Future Method Execution Completed!';
}

Handling the Future method using Future.then() method:

// by pressing the button Future method will start executing for 4 seconds
ElevatedButton(
onPressed: () {
// Fetch data when the button is clicked
// Call the future Method then show
// the result using then() method
fetchData().then((result) {
setState(() {
data = result;
});
});
},
child: Text('Execute Future Method'),
),

Dart




class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
  
class _MyHomePageState extends State<MyHomePage> {
  // Act as a Future Method that 
  // will fetches data from an API.
  Future<String> fetchData() async {
    // Simulate the time take by API request delay
    await Future.delayed(Duration(seconds: 4)); 
    return 'Future Method Execution Completed!';
  }
  
  String data = 'Loading...';
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Future.then() Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(data),
            // by pressing the button Future method 
            // will start executing for 4 seconds
            ElevatedButton(
              onPressed: () {
                // Fetch data when the button is clicked.
                fetchData().then((result) {
                  setState(() {
                    data = result;
                  });
                });
              },
              child: Text('Execute Future Method'),
            ),
          ],
        ),
      ),
    );
  }
}


Here is the full Code of main.dart file:

Dart




import 'dart:async';
import 'package:flutter/material.dart';
  
void main() {
  runApp(MyApp());
}
  
class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
       debugShowCheckedModeBanner: false,
       theme: ThemeData(
        // Set the app's primary theme color
        primarySwatch: Colors.green, 
      ),
      home: MyHomePage(),
    );
  }
}
  
class MyHomePage extends StatefulWidget {
  @override
  _MyHomePageState createState() => _MyHomePageState();
}
  
class _MyHomePageState extends State<MyHomePage> {
  // Act as a Future Method that will 
  // fetches data from an API.
  Future<String> fetchData() async {
    // Simulate the time take by API request delay
    await Future.delayed(Duration(seconds: 4)); 
    return 'Future Method Execution Completed!';
  }
  
  String data = 'Loading...';
  
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Future.then() Example'),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: <Widget>[
            Text(data),
            // by pressing the button Future method 
            // will start executing for 4 seconds
            ElevatedButton(
              onPressed: () {
                // Fetch data when the button is clicked
                // Call the future Method then 
                // show the result using then() method
                fetchData().then((result) {
                    setState(() {
                    data = result;
                  });
                });
              },
              child: Text('Execute Future Method'),
            ),
          ],
        ),
      ),
    );
  }
}


Output:



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads