Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java for Android
  • Android Studio
  • Android Kotlin
  • Kotlin
  • Flutter
  • Dart
  • Android Project
  • Android Interview
Open In App
Next Article:
Flutter - FutureBuilder Widget
Next article icon

Flutter - FutureBuilder Widget

Last Updated : 07 Jun, 2022
Comments
Improve
Suggest changes
Like Article
Like
Report

In Flutter, the FutureBuilder Widget is used to create widgets based on the latest snapshot of interaction with a Future.  It is necessary for Future to be obtained earlier either through a change of state or change in dependencies. FutureBuilder is a Widget that will help you to execute some asynchronous function and based on that function's result your UI will update.

FutureBuilder is Stateful by nature i.e it maintains its own state as we do in StatefulWidgets.

Syntax:

FutureBuilder(   Key key,   this.future,   this.initialData,   @required this.builder, ) And, builder should not be null.

When we use the FutureBuilder widget we need to check for future state i.e future is resolved or not and so on. There is various State as follows:

  1. ConnectionState.none: It means that the future is null and initialData is used as defaultValue.
  2. ConnectionState.active: It means the future is not null but it is not resolved yet.
  3. ConnectionState.waiting: It means the future is being resolved, and we will get the result soon enough.
  4. ConnectionState.done: It means that the future has been resolved.

We will create FutureBuilder Widget in a step by step manner.

Step 1: Create a future that needs to be resolved.

Dart
/// Function that will return a /// "string" after some time /// To demonstrate network call /// delay of [2 seconds] is used /// /// This function will behave as an /// asynchronous function Future<String> getData() {   return Future.delayed(Duration(seconds: 2), () {     return "I am data";     // throw Exception("Custom Error");   }); } 

The above snippet is to demonstrate a real network call. We have used a 2 seconds delay.

Step 2: Create a FutureBuilder Widget and manage the waiting state.

Dart
FutureBuilder(   builder: (ctx, snapshot) {     ... some code here            // Displaying LoadingSpinner to indicate waiting state     return Center(       child: CircularProgressIndicator(),     );   },      // Future that needs to be resolved   // inorder to display something on the Canvas   future: getData(), ), 

In this snippet, we can see we are returning a LoadingSpinner. It will only be displayed when the future is in the Waiting state.

Step 3: Manage Future done state i.e when the future is resolved. This step also requires checking for any error that could occur during a network call.

Dart
FutureBuilder(   builder: (ctx, snapshot) {     // Checking if future is resolved     if (snapshot.connectionState == ConnectionState.done) {       // If we got an error       if (snapshot.hasError) {         return Center(           child: Text(             '${snapshot.error} occurred',             style: TextStyle(fontSize: 18),           ),         );                  // if we got our data       } else if (snapshot.hasData) {         // Extracting data from snapshot object         final data = snapshot.data as String;         return Center(           child: Text(             '$data',             style: TextStyle(fontSize: 18),           ),         );       }     }          ... some code here       ), 

In the above snippet, you can see we are checking

snapshot.hasError This step is require because it could be possible that future is resolved but an error has occurred.

We are also checking

snapshot.hasData This step is required because it may be possible that future is resolved but nothing is returned due to some reasons, so always perform these checks otherwise you may get unexpected behaviour.

Complete Source Code: 
 

Dart
import 'package:flutter/material.dart';  void main() => runApp(MyApp());  class MyApp extends StatelessWidget {   @override   Widget build(BuildContext context) {     return MaterialApp(       title: 'GeeksforGeeks',        // to hide debug banner       debugShowCheckedModeBanner: false,       theme: ThemeData(         primarySwatch: Colors.green,       ),       home: HomePage(),     );   } }  class HomePage extends StatelessWidget {   @override   Widget build(BuildContext context) {     return SafeArea(       child: Scaffold(         appBar: AppBar(           title: Text('GeeksforGeeks'),         ),         body: Center(           child: ElevatedButton(             onPressed: () => Navigator.push(               context,               MaterialPageRoute(                 builder: (ctx) => FutureDemoPage(),               ),             ),             child: Text('Demonstrate FutureBuilder'),           ),         ),       ),     );   } }  class FutureDemoPage extends StatelessWidget {   /// Function that will return a   /// "string" after some time   /// To demonstrate network call   /// delay of [2 seconds] is used   ///   /// This function will behave as an   /// asynchronous function   Future<String> getData() {     return Future.delayed(Duration(seconds: 2), () {       return "I am data";       // throw Exception("Custom Error");     });   }    @override   Widget build(BuildContext context) {     return SafeArea(       child: Scaffold(         appBar: AppBar(           title: Text('Future Demo Page'),         ),         body: FutureBuilder(           builder: (ctx, snapshot) {             // Checking if future is resolved or not             if (snapshot.connectionState == ConnectionState.done) {               // If we got an error               if (snapshot.hasError) {                 return Center(                   child: Text(                     '${snapshot.error} occurred',                     style: TextStyle(fontSize: 18),                   ),                 );                  // if we got our data               } else if (snapshot.hasData) {                 // Extracting data from snapshot object                 final data = snapshot.data as String;                 return Center(                   child: Text(                     '$data',                     style: TextStyle(fontSize: 18),                   ),                 );               }             }              // Displaying LoadingSpinner to indicate waiting state             return Center(               child: CircularProgressIndicator(),             );           },            // Future that needs to be resolved           // inorder to display something on the Canvas           future: getData(),         ),       ),     );   } } 

Output:


Next Article
Flutter - FutureBuilder Widget

S

sanjeev2552
Improve
Article Tags :
  • Technical Scripter
  • Dart
  • Flutter
  • Android
  • Technical Scripter 2020
  • Flutter
  • Flutter-Widgets

Similar Reads

    Flutter - StreamBuilder Widget
    A StreamBuilder in Flutter is used to listen to a stream of data and rebuild its widget subtree whenever new data is emitted by the stream. It's commonly used for real-time updates, such as when working with streams of data from network requests, databases, or other asynchronous sources. In this art
    5 min read
    Flutter - LayoutBuilder Widget
    In Flutter, LayoutBuilder Widget is similar to the Builder widget except that the framework calls the builder function at layout time and provides the parent widget's constraints. This is useful when the parent constrains the child's size and doesn't depend on the child's intrinsic size. The LayoutB
    3 min read
    Flutter - GridPaper Widget
    A grid paper is a paper that has a grid on it with divisions and subdivisions, for example, graph paper. We may use grid paper in creating the graphs in our flutter application. A sample image is given below to get an idea about what we are going to do in this article.  How to use it?Dart GridPaper(
    3 min read
    Flutter - Stepper Widget
    In this article, we will learn about the Stepper widget in Flutter. A stepper widget displays progress through a sequence of steps. A stepper is generally used in filling out forms online.For example, remember filling out an online form for applying to any university or passport, or driving license.
    6 min read
    Flutter - Stateful Widget
    A Stateful Widget has states in it. To understand a Stateful Widget, you need to have a clear understanding of widgets and state management. A state can be defined as "an imperative changing of the user interface," and a widget is "an immutable description of the part of the user interface". To lear
    4 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences