Open In App

Flutter – What is Future and How to Use It?

Last Updated : 08 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

Future in Flutter refers to an object that represents a value that is not yet available but will be at some point in the future. A Future can be used to represent an asynchronous operation that is being performed, such as fetching data from a web API, reading from a file, or performing a computation. A Future in Flutter is typically used in combination with the “async” and “await” keywords to perform asynchronous operations in a non-blocking way.  Here’s an example of how you might use a Future in Flutter to fetch data from a web API.

Dart




Future<String> fetchSomeData() async {
  // Make an HTTP request to fetch some data
  final response = await http.get(Uri.parse('https://example.com/api/some-data'));
  
  // Extract the response body as a string
  final responseBody = response.body;
  
  // Return the response body as a string
  return responseBody;
}


In this example, we define a function called fetchSomeData that returns a Future<String>. The function uses the http package to make an HTTP request to a web API and fetch some data. The await keyword is used to wait for the HTTP request to complete, and then the response body is extracted as a string and returned. To use this function in your Flutter app, you can simply call it like this:

Dart




fetchSomeData().then((data) {
  // Do something with the data
});


In this example, we call fetchSomeData and use the then method to register a callback function that will be called when the Future completes and the data is available. The callback function takes the data as a parameter, so you can do whatever you need to do with it inside the callback.

Code Example: 

Dart




import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
  
void main() {
runApp(RunMyApp());
  
class RunMyApp extends StatefulWidget {
  @override
  _RunMyAppState createState() => _RunMyAppState();
}
  
class _RunMyAppState extends State<RunMyApp> {
  String _data = 'Loading...';
  
  Future<void> _fetchData() async {
    final response = await http
        .get(Uri.parse('https://jsonplaceholder.typicode.com/todos/1'));
    if (response.statusCode == 200) {
      final body = json.decode(response.body);
      setState(() {
        _data = 'Title: ${body['title']}, Completed: ${body['completed']}';
      });
    } else {
      setState(() {
        _data = 'Failed to fetch data';
      });
    }
  }
  
  @override
  void initState() {
    super.initState();
    _fetchData();
  }
  
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(primarySwatch: Colors.green),
      title: 'Flutter Future Example',
      home: Scaffold(
        appBar: AppBar(
          title: Text('Flutter Future Example'),
        ),
        body: Center(
          child: Text(_data),
        ),
      ),
    );
  }
}


Output:

Explanation:

In this example, we define a stateful widget called MyApp that has a _data property to hold the data fetched from the web API. In the initState method, we call _fetchData to fetch the data and update the state.

The _fetchData method is defined as an async function that makes an HTTP request using the http package and then decodes the response body using the json package. If the request is successful, the _data property is updated with the title and completed the status of the first to-do item returned by the API. If the request fails, the _data property is set to an error message.

In the build method, we display the _data property in a Text widget that is centered on the screen. When the app is run, it will display the message “Loading…” until the data is fetched from the web API, at which point it will display the title and completed status of the first to-do item.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads