Dart Programming - Async

An asynchronous operation executes in a thread, separate from the main application thread. When an application calls a method to perform an operation asynchronously, the application can continue executing while the asynchronous method performs its task.

Example

Let’s take an example to understand this concept. Here, the program accepts user input using the IO library.

import 'dart:io'; 
void main() { 
   print("Enter your name :");            
   
   // prompt for user input 
   String name = stdin.readLineSync();  
   
   // this is a synchronous method that reads user input 
   print("Hello Mr. ${name}"); 
   print("End of main"); 
} 

 

The readLineSync() is a synchronous method. This means that the execution of all instructions that follow the readLineSync() function call will be blocked till the readLineSync() method finishes execution.

The stdin.readLineSync waits for input. It stops in its tracks and does not execute any further until it receives the user’s input

Output

Enter your name :     
Tom                   

// reads user input  
Hello Mr. Tom 
End of main

 

In computing, we say something is synchronous when it waits for an event to happen before continuing. A disadvantage in this approach is that if a part of the code takes too long to execute, the subsequent blocks, though unrelated, will be blocked from executing. Consider a webserver that must respond to multiple requests for a resource.

A synchronous execution model will block every other user’s request till it finishes processing the current request. In such a case, like that of a web server, every request must be independent of the others. This means, the webserver should not wait for the current request to finish executing before it responds to request from other users.

Simply put, it should accept requests from new users before necessarily completing the requests of previous users. This is termed as asynchronous. Asynchronous programming basically means no waiting or non-blocking programming model. The dart:async package facilitates implementing asynchronous programming blocks in a Dart script.

Example

The following example better illustrates the functioning of an asynchronous block.

Step 1 − Create a contact.txt file as given below and save it in the data folder in the current project.

1, Java
2, Dart
3, Flutter
4, Kotlin

Step 2 − Write a program which will read the file without blocking other parts of the application

 

import "dart:async"; 
import "dart:io";  

void main(){ 
   File file = new File( Directory.current.path+"\\data\\contact.txt"); 
   Future<String> f = file.readAsString();  
  
   // returns a futrue, this is Async method 
   f.then((data)=>print(data));  
   
   // once file is read , call back method is invoked  
   print("End of main");  
   // this get printed first, showing fileReading is non blocking or async 
}

 

Output

End of main 
1, Java 
2, Dart 
3, Flutter 
4, Kotlin

 

Dart Future

The Dart community defines a Future as "a means for getting a value sometime in the future." Simply put, Future objects are a mechanism to represent values returned by an expression whose execution will complete at a later point in time. Several of Dart’s built-in classes return a Future when an asynchronous method is called.

Dart is a single-threaded programming language. If any code blocks the thread of execution (for example, by waiting for a time-consuming operation or blocking on I/O), the program effectively freezes.

Asynchronous operations let your program run without getting blocked. Dart uses Future objects to represent asynchronous operations



Flutter Examples

  • Flutter Screenshot Widget - Take sceenshot as capture Image
  • Flutter Migrate App to Null Safety | Flutter 2.0
  • Flutter 2.0 Autocomplete TextField | RawAutocomplete Example
  • How to check installed Flutter Version
  • Info Popup Window | Create Popup window in Flutter Listview
  • Flutter Flow widget Example
  • Flutter GetX Storage | SharedPreferences
  • Send Email From Flutter Application | Attach html documents to email
  • Auto SMS OTP Read in Flutter Android
  • Download Files inside Listview | View Downloaded Files Flutter
  • Travel App Profile Page | Flutter Profile Page Example 2
  • Flutter Photo View | Image Zoom like Gallery App
  • Generate Signed APK for Flutter Application with Andorid Studio
  • Flutter Stacked Item ListView | Scroll Animation
  • Flutter Horizontal Listview with a Snap Effect
  • Infinite scrolling list with Flutter - Flutter Pagination Example
  • Flutter Audio Recording Example
  • Show BottomSheet Dialog On Screen Load - Flutter
  • Flutter Device Info | Read Device Info on Android and iOS devices with device_info plugin
  • Play YouTube video | YouTube API integration in Flutter
  • Dynamic ExpansionTile | Create Expansion List with Dynamic Data
  • Keyboard Request Focus Flutter Example | Handle Keyboard Next Button Events
  • Alert Dialog with Close Button Button
  • Share Location | How do i share current location in flutter
  • Copy flutter assets database inside application
  • End to End Encryption Decryption in Flutter
  • 3D Model Viewer in Flutter
  • File Read and Write Operations in Flutter Application - File I/O Operation
  • How to show Listview inside Dialog in Flutter
  • Store Image as String in SQLite Database in Flutter
  • Flutter interview questions with answers
  • A complete list of Flutter Libraries & Packages used for Flutter App development
  • Flutter bottom navigation - Simple BottomNavigationBar Example
  • How to Implement Pull To Refresh in Flutter?
  • User Registration and Login with Flutter and PHP Rest API
  • Design Complex UI in Flutter - Animated Drawer Widget
  • Building a Flutter app with DateTime Picker - Get DateTime From DateTime String
  • Dart Convert Map to List & List to Map
  • Create Circle Image in Flutter
  • Display multiple images inside grid like facebook in Flutter
  • Flutter consume data with Http Get and Http Post
  • Beehive Layout Widget in Flutter
  • Nested Listview (Listview inside Listview) in Flutter
  • How to Access Contacts in Flutter Application (Read and Make Phone calls)
  • MultiSelection Listview in Flutter with CheckboxListTile
  • Snackbar on Flutter (without Scaffold) using Flushbar
  • Flutter Transparent Background Page
  • Create Custom Widget in Flutter - Download Indicator
  • How To Open A Word or PDF Document On Android
  • Android TV Support with Flutter Framework
  • Check Network Connectivity Status in Flutter - Online & Offline Connectivity
  • Horizontal Scrollable Table in Flutter
  • REST API integration in Flutter with Retrofit
  • Expandable Card - BottomSheet Widget Flutter
  • Upload Image to Firebase Storage - Flutter (Android & Ios)
  • ListWheelScrollView Flutter Example
  • ChangeNotifierProvider - Flutter
  • Image Picker Flutter - Take Image From Camera or Gallery
  • How to show or hide widget in Flutter
  • Flutter - How to Run Background Task? Service
  • Text widget with read more or expand feature - Flutter
  • Create Profile Page in Flutter - UI
  • How to convert BASE64 string into Image with Flutter?
  • How to Show Back Button in Flutter
  • 10 Innovative apps that are built using Flutter
  • Flutter Push Notifications using flutter firebase messaging with example
  • How to create rating bar dialog in Flutter App
  • Flutter - Using DraggableScrollableSheet Widget Examples
  • How to parse RSS Feed in Flutter?
  • Flutter: Page View
  • Create native settings Page UI in Flutter
  • Delete data from Firestore - Delete Collection and subcollections
  • FloatingActionButton - Animated FloatingActionButton in Flutter
  • FireStore CRUD in Flutter - Social Application
  • Flutter Chat UI Tutorial
  • Flutter Food Ordering App Theme Template
  • Flutter Social Forum Application
  • Flutter State Management - ScopedModel
  • Flutter Todo Application Themes
  • Profile Themes
  • Login Themes
  • Localization Flutter - ChangeNotifier
  • How to show Checkbox at Right side of Text - Flutter
  • How to get Device Id in Flutter
  • Google Translator - Flutter
  • Building chat app with Flutter and Firebase
  • Shared Preferences - Data Persistence Flutter
  • Login Page - FrostedGlass Background Flutter
  • Simple Animation in Flutter
  • Settings Button - Flutter Popup Menu Button
  • Color Picker - Flutter Material Color Picker
  • Read Inbox Messages - Flutter SMS Retriever
  • Social Auth Buttons - Flutter (Google,Facebook,Twitter,Microsoft,Linked)
  • Credit Card Validator - Flutter
  • StreamBuilder - Flutter
  • Switch Button-Custom Switch-Flutter
  • Custom Toast - Flutter
  • Text Shadows in Flutter
  • How to load Html Content in Flutter
  • HOW TO ADD TEXTFIELD IN ALERT DIALOG IN FLUTTER
  • Firebase authentication & Google sign in using Flutter
  • How to add Firebase setup in Flutter
  • Flutter Fingerprint Authentication
  • Download Files in Flutter (Pdf, Json, Image etc) With Progress : Flutter Advance
  • Flutter Stepper Example - CREATE A SIMPLE STEPPER WITH FLUTTER
  • Flutter Custom Buttons - How to Create Custom Buttons in Flutter?
  • HOW TO SCAN QR CODE WITH FLUTTER
  • Flutter Responsive Admin Template -2
  • Flutter Responsive Admin Template
  • Flutter Facebook Login - A Complete Guide to Facebook login with Flutter
  • Flutter - How to create Digital Signature pad (ESignature iOS and Android)
  • Flutter Future Builder
  • Flutter Radio Groups - How to make a list of grouped radio buttons in flutter
  • Form Builder in Flutter - Form Validation | RRTutors
  • Make Shimmer Effect in Flutter
  • Flutter Voice Recognition- Speech To Text - Voice Based Search
  • Text-to-Speech Flutter Plugin (Android & iOS)
  • Flutter - Page Navigation, Navigator and Routes - How to get Result from Screen
  • Flutter Form & Form-Fields widgets With Login Screen
  • Appbar Search | Implementing Search action with AppBar in flutter
  • Flutter Screen Navigation with Animation
  • Flutter - Bottomnavigationbar - PageView - Reload Page - KeepLive Pages
  • Flutter Stateful widget - Part3 - InheritedWidget Example - Sample Post List
  • Flutter Stateful widget - Part2 - How to Access State of Widget
  • Flutter Stateful widget - Part1 - Introduction - Lifecycle Methods
  • Push Notification in Flutter - Local Notification Part -2
  • Push Notification in Flutter - Local Notification
  • PIN Input Field in Flutter
  • Building Beautiful UI Interfaces with Flutter-Basic Components
  • Flutter - How to use Lottie Animations in Flutter
  • How to display Text Vertically
  • Flutter SafeArea - Handle start position of Widgets in the screen
  • Flutter Carousel - Swiper Banners
  • SelectableText widget vs Text widget Flutter - Text copy to Clipboard
  • Flutter Sensors - Accelerator Mobile Shake Events
  • How To Use Custom Icons in Flutter
  • Flutter - Custom Sticky Headers
  • Webview in flutter - Open Local HTML file in to webview - Open URL in Webview- handle Javascript function in webview
  • Flutter - How can draw route on google map between two locations?
  • Current Location On Maps - Flutter, Fetch Current Location Address.
  • How to dynamically change the theme in Flutter - ThemeProvider
  • Show Multiple Markers on Google Maps - Flutter infowindow example
  • Google Maps in Flutter, How to Load Google Maps
  • Flutter - ListView - Search Filter - NewsApplication
  • TabBar in Flutter, Custom TabBar, BottomNavigationbar, Different Styles of TabBar
  • Flutter GridView with Builder Constructor
  • Flutter GridView and Different ways of Constructors
  • ToogleBar - Flutter
  • Read Json file from assets folder - Flutter
  • Expandable Listview | Expansion/Collapse view | ExpansionTile
  • Flutter - Drag & Drop Listview - Reorderable Listview
  • Bottom Navigation Bar - TabBarView
  • Firebase Integration, Firebase Authentication, Firestore | RRTutors
  • Flutter - Dashboard App | RRTutors
  • Flutter SQFLite Tutorial: Implement SQFLite database in Flutter | RRTutors
  • Flutter Button Widgets | RRTutors
  • Flutter Widgets | RRTutors
  • Flutter First Application | RRTutors
  • Flutter Introduction | RRTutors
  • Android Examples

  • Android Onboarding Screen UI with ViewPager
  • What is View Binding | Android View Binding Example
  • How do i use Navigationview in android with Kotlin
  • Start activity From Fragment Android Example
  • Android ViewModel Interview Questions and Answers
  • GooglePlay Inapp Review API Integration in Android Application
  • Easy way To Convert Website Into Mobile Application Android
  • Order and Un Order List in Android Textview Kotlin
  • Dialog Fragment with Scroll view - doesn't scroll | Android studio Project
  • Color Picker | Android Color Picker view to set Color to Bulb View
  • Jetpack Compose Tutorial | Jetpack Compose Basics
  • Get List of devices connected to Same Network in Android Programmatically
  • How to display Listview inside Dialog in Android | Kotlin Example
  • How to add Image and text in Sqlite Database and Display it in recyclerView with kotlin
  • Getting Started with Facebook Analytics for Mobile Apps
  • Android Job Scheduler with Kotlin
  • Understanding The Lifecycle of Custom View In Android - Kotlin
  • How to create pagination text in Android using Kotlin?
  • Re-size and Compress Image in Android Studio
  • Dependency Injection - What is Dependency Injection?
  • One to One chat application using Kotlin - Android
  • Integrating UPI payments in an Android application
  • Android Jetpack Tutorials : LiveData
  • Android ViewModel Tutorial : Jetpack Tutorials : View Model Introduction
  • How To Use Jet Pack Components BottomNavigationView With Navigation Ui
  • In-App purchase Google Play Billing - Play Billing Library
  • Taking a screenshot of a particular view
  • Handler in Android
  • Add Google Analytics in Android Application
  • Adding Firebase to Android App
  • How to create Circular Seekbar in Android
  • ANDROID GOOGLE MAPs Marker | Custom MARKER CLUSTERING
  • Android Q - Settings Panel
  • Image Slider in Android
  • Create and Display Notification on Android
  • Foreground Service Android
  • Android Combine Two Images| HOW TO COMBINE MULTIPLE IMAGES TO A SINGLE IMAGE IN ANDROID
  • How to change Orientation programmatically in Android
  • How to uninstall/delete APK Programmatically in Android
  • Android - Kotlin - ContextMenu - How to Create Contextmenu in Android?
  • Kotlin - How to handle swipe Gesture in Android Application?
  • Android Switch (ON / OFF) Button - Custom Style
  • Android - Softinput Keyboard open and close programmatically
  • Kotlin - Android Textwatcher Example
  • How to set the part of the Android TextView as clickable - ClickableSpan
  • Kotlin – Android Color Picker Example
  • Create Custom Snackbar - How to use snackbar in Android?
  • How to call an activity method from fragment | Start Activity from Fragment
  • How to Create Android Calculator Application
  • Android kotlin - SeekBar example
  • Android Animations - Rotate,Scale,Translate,Zoom animations in Android
  • Live WallPaper - How to Make Interactive Live Video Wallpapers Using Kotlin Android
  • Kotlin Create Slider With Page Indicator Using ViewPager Example
  • Android kotlin - AlertDialog example
  • Android - Kotlin Success and Error Dialogs with Lottie Animation
  • Android-Kotlin - Circular Imageview with Border
  • SwipeRefreshLayout - Android
  • Android Bottom Sheet with BottomSheetDialogFragment
  • Android Exoplayer - Play Audio/Video files in Android.
  • What is Retrofit and how to use Retrofit in Android?
  • Firebase Project - Android
  • Android Video Player Example
  • Test
  • Programming Vocabulary
  • Moving Map Under Marker Like UBER: Maps Android, Kotlin | RRTutors
  • Circular Progress bar with Thumb | RRTutors