Flutter – Handling Asynchronous Data
Asynchronous events in Flutter, refer to events that do not occur immediately and may take some time to complete. They typically involve asynchronous operations, allowing your application to continue executing other tasks while waiting for the asynchronous operation to finish. Asynchronous events are essential for handling tasks such as network requests, file I/O, and user interactions that might introduce delays or uncertainties in how long they take to complete. In Flutter, we can use streams for handling asynchronous events. In this article, we are going to handle the asynchronous data events using Streams class in Flutter. A sample video is given below to get an idea about what we are going to do in this article.
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: StreamDemo(), ); } } |
Step 5: Create StreamDemo Class
In this class we are going to implement Streams class with a combination of StreamBuilder to handler asynchronous data events. When the user press the Floating action Button we act as the data is coming from an network source.Comments are added for better understanding.
Dart
class StreamDemo extends StatefulWidget { @override _StreamDemoState createState() => _StreamDemoState(); } class _StreamDemoState extends State<StreamDemo> { // Create a StreamController for handling a stream of strings StreamController<String> _streamController = StreamController<String>(); @override void dispose() { // Close the stream controller // when done to avoid resource leaks _streamController.close(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text( 'Stream Demo' ), ), body: Center( child: StreamBuilder<String>( stream: _streamController.stream, builder: (context, snapshot) { if (snapshot.hasError) { return Text( 'Error: ${snapshot.error}' ); } if (!snapshot.hasData) { return Text( 'No data' , style: TextStyle(fontWeight: FontWeight.bold)); } return Text( 'Data: ${snapshot.data}' , style: TextStyle(fontWeight: FontWeight.bold)); }, ), ), floatingActionButton: FloatingActionButton( onPressed: () { // Acting as data coming from an asynchronous source Future.delayed(Duration(seconds: 2), () { // Add data to the stream _streamController.sink.add( 'Hello, Flutter!' ); }); }, child: Icon(Icons.send), ), ); } } |
In this above code:
- We create a StreamController<String> named _streamController to manage the stream of string data.
- In the StreamDemo widget’s build method, we use a StreamBuilder widget. It listens to the stream provided _streamController.stream and rebuilds the UI whenever new data arrives.
- Inside the floatingActionButton, we simulate data arriving asynchronously by adding “Hello, Flutter!” to the stream after a delay of 2 seconds when the button is pressed.
- When the app is closed or disposed, we make sure to call _streamController.close() to properly close the stream controller.
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: StreamDemo(), ); } } class StreamDemo extends StatefulWidget { @override _StreamDemoState createState() => _StreamDemoState(); } class _StreamDemoState extends State<StreamDemo> { // Create a StreamController for handling a stream of strings StreamController<String> _streamController = StreamController<String>(); @override void dispose() { // Close the stream controller // when done to avoid resource leaks _streamController.close(); super.dispose(); } @override Widget build(BuildContext context) { return Scaffold( appBar: AppBar( title: Text( 'Stream Demo' ), ), body: Center( child: StreamBuilder<String>( stream: _streamController.stream, builder: (context, snapshot) { if (snapshot.hasError) { return Text( 'Error: ${snapshot.error}' ); } if (!snapshot.hasData) { return Text( 'No data' , style: TextStyle(fontWeight: FontWeight.bold)); } return Text( 'Data: ${snapshot.data}' , style: TextStyle(fontWeight: FontWeight.bold)); }, ), ), floatingActionButton: FloatingActionButton( onPressed: () { // Acting as data coming from an asynchronous source Future.delayed(Duration(seconds: 2), () { // Add data to the stream _streamController.sink.add( 'Hello, Flutter!' ); }); }, child: Icon(Icons.send), ), ); } } |