Google search engine
Home Blog Page 55

How to build a music player in Flutter 2026

Things that you may likely learn from the Blog :

Before starting the blog let me tell you what you can learn from this blog:-

In this blog, you will learn how to implement a music player into your flutter app.

  • How to fetch the music from external storage, play from assets file , how to play the music using a URL(internet).
  • Controlling the volume of the music player.
  • How to pause and play the song.

Demo of App ::

DEMO.gif: {Working gif of module}

Video :

new.mp4
Edit descriptiondrive.google.com


Introduction

Music is a language of emotions. Music apps have become an apparent hit and need of the times. Users are using different music apps to listen up to their favourite songs to help them relieve stress or in Improving their creative ability.

As an app developer, you must make some apps that you can use in your daily life. So I tried to make a personal music app, hoping that you will also like it. In this blog, I will help you to build your basic music app using flutter.😊😊

Table of content::

  1. Packages used
  2. Setting up the project
  3. Playing music using the internet and assets
  4. Fetching music files from our external storage.
  5. Setting up the audio
  6. Creating a Control panel
  7. GitHub Link

Packages used::

We will use flutter_audio_query to fetch the music form our external storage(eg. mobile phone, memory card, etc).

flutter_audio_query | Flutter Package
A Flutter plugin, Android only at this moment, that allows you query for audio metadata info about artists, albums…pub.dev

audio_manager package provides us various methods and functions to implement functionality in our app such as play, pause, seek, inc. or dec. volume.

audio_manager | Flutter Package
A flutter plugin for music playback, including notification handling. This plugin is developed for iOS-based on…pub.dev

Setting up the project::

import the packages

import 'package:flutter_audio_query/flutter_audio_query.dart';
import 'package:audio_manager/audio_manager.dart';

Modify your AndroidManifest.xml

<application
...
android:usesCleartextTraffic="true"
...
>

Modify your build.gradle file.

defaultConfig {
minSdkVersion 23
}

Playing music using internet and assets::

Creating an audio manager instance

var audioManagerInstance = AudioManager.instance;

Playing music using the start method

AudioManager provides us start() method to play the music. It takes a URL, title, description, cover, and auto.

onTap: () {
audioManagerInstance
.start("song URL", "song title",
desc: "description",
auto: true,
cover: "cover URL")
.then((err) {
print(err);
});
},

To play the music file using assets file you just need to change the song URL to assets file path.

onTap: () {
audioManagerInstance
.start("assets/music.mp3"song title",
desc: "description",
auto: true,
cover: "assets/cover.png")
.then((err) {
print(err);
});
},

Fetching music files from our external storage::

To fetch the music files form the external storage we will use a FutureBuilder as FlutterAudioQuery returns a future . This class provides us various methods such as getSongs, getSongsFromArtist , getSongsFromAlbum , getSongsFromArtistAlbum , etc.

To keep the logic simple and sleek we will only use getSongs method. You can use as many as you want.

FutureBuilder(
future: FlutterAudioQuery()
.getSongs(sortType: SongSortType.RECENT_YEAR),
builder: (context, snapshot) {
List<SongInfo> songInfo = snapshot.data;
if (snapshot.hasData) return SongWidget(songList: songInfo);
return Container(
height: MediaQuery.of(context).size.height * 0.4,
child: Center(
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
CircularProgressIndicator(),
SizedBox(
width: 20,
),
Text(
"Loading....",
style: TextStyle(fontWeight: FontWeight.bold),
)
],
),
),
);
},
)

SongWidget

To play the music from the external memory we require a path of that song. SongInfo class provides us filePath property to get the path of the music file.

onTap: () {
audioManagerInstance
.start("file://${song.filePath}", song.title,
desc: song.displayName,
auto: true,
cover: song.albumArtwork)
.then((err) {
print(err);
});
},

https://gist.github.com/anmolseth06/11a33c09b1b4f085494835b1b55bb263#file-songwidget-dart

Setting up the audio::

This is the most important part, because this contolles various events of audio.

void setupAudio() {
audioManagerInstance.onEvents((events, args) {
switch (events) {
case AudioManagerEvents.start:
_slider = 0;
break;
case AudioManagerEvents.seekComplete:
_slider = audioManagerInstance.position.inMilliseconds /
audioManagerInstance.duration.inMilliseconds;
setState(() {});
break;
case AudioManagerEvents.playstatus:
isPlaying = audioManagerInstance.isPlaying;
setState(() {});
break;
case AudioManagerEvents.timeupdate:
_slider = audioManagerInstance.position.inMilliseconds /
audioManagerInstance.duration.inMilliseconds;
audioManagerInstance.updateLrc(args["position"].toString());
setState(() {});
break;
case AudioManagerEvents.ended:
audioManagerInstance.next();
setState(() {});
break;
default:
break;
}
});
}

initializing setupAudio

void initState() {
super.initState();
setupAudio();
}

Creating a control pannel::

This panel has a playpause button, previous button, next button, and a songProgress Slider .

Widget bottomPanel() {
return Column(children: <Widget>[
Padding(
padding: EdgeInsets.symmetric(horizontal: 16),
child: songProgress(context),
),
Container(
padding: EdgeInsets.symmetric(vertical: 16),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[
CircleAvatar(
child: Center(
child: IconButton(
icon: Icon(
Icons.skip_previous,
color: Colors.white,
),
onPressed: () => audioManagerInstance.previous()),
),
backgroundColor: Colors.cyan.withOpacity(0.3),
),
CircleAvatar(
radius: 30,
child: Center(
child: IconButton(
onPressed: () async {
if(audioManagerInstance.isPlaying)
audioManagerInstance.toPause();
audioManagerInstance.playOrPause();
},
padding: const EdgeInsets.all(0.0),
icon: Icon(
audioManagerInstance.isPlaying
? Icons.pause
: Icons.play_arrow,
color: Colors.white,
),
),
),
),
CircleAvatar(
backgroundColor: Colors.cyan.withOpacity(0.3),
child: Center(
child: IconButton(
icon: Icon(
Icons.skip_next,
color: Colors.white,
),
onPressed: () => audioManagerInstance.next()),
),
),
],
),
),
]);
}

Song Duration

This function is used to format the duration of the song this is in millisecond format, we will convert it into this format 00:00 .

Here format is a string 00:00 . _formatDuration takes the duration of the song. If the duration is null then it returns — : — otherwise it returns the duration in the given format.

String _formatDuration(Duration d) {
if (d == null) return "--:--";
int minute = d.inMinutes;
int second = (d.inSeconds > 60) ? (d.inSeconds % 60) : d.inSeconds;
String format = ((minute < 10) ? "0$minute" : "$minute") +
":" +
((second < 10) ? "0$second" : "$second");
return format;
}

SongProgress

Widget songProgress(BuildContext context) {
var style = TextStyle(color: Colors.black);
return Row(
children: <Widget>[
Text(
_formatDuration(audioManagerInstance.position),
style: style,
),
Expanded(
child: Padding(
padding: EdgeInsets.symmetric(horizontal: 5),
child: SliderTheme(
data: SliderTheme.of(context).copyWith(
trackHeight: 2,
thumbColor: Colors.blueAccent,
overlayColor: Colors.blue,
thumbShape: RoundSliderThumbShape(
disabledThumbRadius: 5,
enabledThumbRadius: 5,
),
overlayShape: RoundSliderOverlayShape(
overlayRadius: 10,
),
activeTrackColor: Colors.blueAccent,
inactiveTrackColor: Colors.grey,
),
child: Slider(
value: _slider ?? 0,
onChanged: (value) {
setState(() {
_slider = value;
});
},
onChangeEnd: (value) {
if (audioManagerInstance.duration != null) {
Duration msec = Duration(
milliseconds:
(audioManagerInstance.duration.inMilliseconds *
value)
.round());
audioManagerInstance.seekTo(msec);
}
},
)),
),
),
Text(
_formatDuration(audioManagerInstance.duration),
style: style,
),
],
);
}

Github link::

flutter-devs/music_app_demo
A new Flutter application. This project is a starting point for a Flutter application. A few resources to get you…github.com


If you find anything that could be improved please let me know, I would love to improve.💙

If this article has helped you a bit and found interesting please clap!👏


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.

Native vs Hybrid vs Cross-Platform — What To Choose?

0

With the constantly gaining enthusiasm towards the development of apps for mobile devices, there has been a myriad of questions & lots of confusion over cross-platform vs native vs hybrid app development approaches, particularly from new developers. The lack of enough end-to-end resources for choosing the right mobile app approach has continued to serve as a major barrier to finding a lasting solution for the iOS vs Android banter.

Even so, given that both platforms are critical for a fruitful mobile app strategy, cross-platform mobile app development might seem to be the best answer for this debate. Today it is no longer tenable to simply build an app that targets only one platform —Diversity is the key. We need multi-platform apps that can support both Android and iPhone smartphones and ensure no one is left out.

Native Mobile Apps

A native app is usually written in one programming language for a particular operating system. Compared to other types of products, native apps offer consistent performance and are times more reliable. Depending on the platform an app is developed for, specific programming languages are used. For iOS, it’s mainly Objective-C and Swift, while Android developers write in Java or Kotlin.

Going native is a dream of a lot of app owners, but not all can afford it. The biggest reason is, to run the app on multiple platforms, it requires developing and maintaining an app for each platform separately. And it costs a bomb to develop a Native app for multiple platforms to many business people.

Simply put, Native Apps mean building two different apps with different sets of code for each platform Android & iOS.

More Development Time equals More Development Cost.

Consider Building a Native Application If:

  • Users never used your product before (as a web application, for instance)and this is the first time you are making an app public and you want to impress them with the best experience possible.
  • You want to take advantage of device-specific features — camera, GPS, etc.
  • The app is going to be used by a large number of people or has complex features that would be a nightmare to bugfix is a cross-platform app and impossible to load as a hybrid one
  • You want to get a base of DAUs (Daily Active Users)in order to get VC investors to fund the product, so the app needs to be as intuitive and easy-to-learn as possible

Pros Of Building a Native App

High Speed

Thanks to the fact that native mobile applications don’t have a code that’s too complex, they tend to work faster than other apps. Many app elements are displayed quickly because they are preloaded beforehand.

Works Well Offline

Native apps work with no issues even when there’s no internet connectivity. Obviously, that makes such an application way more convenient to users as they can access all the features on the go or on the airplane when there’s no connection.

Cons Of Building a Native App

No reusable code

If a developer wants to create native apps both for Android and iOS, he would have to develop two separate native apps (just what we discussed). Obviously, that would take a lot more time and effort than developing one cross-platform mobile app with a reusable codebase or a hybrid app with a shared backend code.

Involves More Talent

As native apps are language-specific to the core, companies usually struggle to find a skilled developer to pull off developing a native app back-to-back. When comparing native app vs cross-platform app, if a company wants to reach out to a wider audience, they’d have to hire two development teams for native app development. Whereas it could have gone with just one in the case of cross-platform.

Native App Examples

Most of the apps smartphone users install on a daily basis are native. Here are some of the most prominent examples of what native app development is capable of.

Google Maps

Google Maps is a native app available for both Android and iOS. Both apps have common features — street view, turn-by-turn navigation, public transit information, etc. As a native app, Google Maps is able to profit from the device’s built-in features. While it does need online access to be used to its full performance, Google Maps can be displayed in an offline mode as well.

LinkedIn

LinkedIn is another example of an application that switched from a hybrid to a native app. The quality decrease when it comes to performance, slower rendering speed, and storage space issues due to the increasing amount of daily active users forced LinkedIn to consider native apps as a development vector.

Hybrid Mobile Apps

Hybrid apps are the golden mean between native and web applications. They consist of two parts — backend code and a native viewer that can be downloaded to display the backend in a web view. Unlike web apps, hybrid mobile apps don’t require a browser for access and can take advantage of any plugin and the APIs of a device. They are cheaper in development than native apps but their performance is mostly slower as well.

Consider Building a Hybrid Application If:

  • You want the app to run on different platforms but you don’t have the time to develop a cross-platform solution
  • You want to make use of the device’s native features — camera, GPS, etc.
  • You want to distribute a web application across application stores

Pros Of Building a Hybrid App

Faster Development

Due to the fact that the app uses the same backend code for all platforms, it doesn’t take too much time to create a hybrid app. Basically, all a developer has to do is to create a native shell to view the code that has already been developed as a web app. Keep in mind, however, that hybrid apps with lots of features can be even more time-consuming so it’s better to keep it simple.

Simple Maintenance

Due to the fact that hybrid apps are based on web technology, they are easier to maintain compared to native vs hybrid apps that is more complex in terms of coding.

Cons of Building a Hybrid App

Impossible to access Offline

Due to the fact that hybrid apps are essentially web-based, they don’t work without the Internet connection. Moreover, as all the elements of the app have to be loaded, the performance speed is generally slower. Needless to say, this imposes a ton of connection limitations on the application user. Connection issues are a significant difference between native and hybrid app development.

OS Inconsistencies

Due to the fact that hybrid apps share a codebase, certain features might be supported by Android and not displayed on an iOS device and vice versa. It takes more testing sprints to identify inconsistencies and a ton of modifications to fix these issues.

Hybrid App Examples

While at first glance hybrid apps might seem like nothing but a cheap fix, in reality, a fair share of top social media applications is, in fact, hybrid. Let’s take a look at most popular hybrid app examples:

Gmail

Gmail is the most popular email provider in the world at the moment. It has been a web HTML-application for a long time. Gmail’s mobile application is a powerful combination of the native web-application infrastructure and native application.

The hybrid application for Gmail is just as solid in its performance as its PC version. The high customization level and dozens of features prove that hybrid application can be just as rewarding as a native one in the long run.

Instagram

Using the hybrid development approach allowed developers to create an app that supports rich media. While the Instagram feed can’t be refreshed when there’s no Internet connection, you can still access data that has been loaded already.

As of now, Instagram has over a billion downloads. This proves the convenience and power of hybrid apps.

Cross-Platform Mobile Apps

There are distinct operating systems running on various smartphones with Android and iOS featuring as the most widely used. Each of these platforms utilizes a distinctive programming environment with its own language and API.

As such, the need by mobile developers to reach the largest possible user-base, regardless of their preferred platform has given rise to more value being seen in a cross-platform mobile app. Tools like Xamarin have made cross-platform app development widely popular and accessible.

Why a Cross-Platform App?

Applications created utilizing a cross-platform framework are free from OS impulses and thus offer multi-platform usefulness. They provide an incredible solution when you need to release a mobile app on different platforms at a low cost or constrained budget in terms of money, time, and effort.

Pros of Building a Cross-Platform App

Cost-Effective

The issue of native app vs cross-platform apps can be debated but when it comes to cost efficiency, cross-platform development beats the latter hands down. In addition to most cross-platform development tools being unreservedly available, the approach further spares the cost of having to contract separate developers to create apps for different platforms.

Reusable

With cross-platform apps, developers no longer have to write unique code for each operating system. They can instead use a common codebase to transfer the code to different platforms.

Cons of Building a Cross-Platform App

Complex Development Pross

It takes a skilled developer to create an application that would be well-adapted to a few platforms. Basically, there’s a need to keep all the little differences between operating systems and the hardware they run on especially when it comes to implementing a complex interface and features.

Challenging Integrations

Developers can experience difficulties while integrating cross-platform applications to local settings and engaging a third-party cloud service provider. The code of an HTML5 cross-platform app is complicated as the result of callback-style programming used to communicate with native plugins.

Cross-Platform App Examples

There are dozens of cross-platform apps that we use every day. They prove the efficiency of cross-platform development as well as the benefit from creating products for a few platforms with tools like React or Nativescript simultaneously.

Facebook

Back in 2012, Mark Zuckerberg stated at a TechCrunch Disrupt conference: “The biggest mistake we’ve made as a company is betting on HTML5 over native.” He noted that the experience of maintaining a native app on iOS has proven to be faster in the long run and more liberating than the hybrid approach the company used before. Hybrid apps are known to be quite slow for users, and, as a high-traffic application, Facebook needed to provide as fast and seamless of an experience as possible. That’s why the company has shifted from HTML to React Native — a framework designed to create native Android and iOS apps.

Skype

Skype has been around for quite a while now — it is widely used across various devices and operating systems. In fact, a famous communication tool is a cross-platform app developed with Electron. On a PC scale, it shares a codebase between Windows and Linux. When it comes to smartphones, Skype has a cross-platform iOS/Android app.

The user experience of Skype doesn’t suffer from system limitations or a complex codebase. In fact, last year, the development team completely redesigned the app to make sure it looks native-alike.

Slack

Slack is proof that a cross-platform app can still have a ‘native’ feel to it. Apart from simplifying the group communication process, Slack enables access to bots and can help operate various day-to-day work tasks.

Over the span of just a few years, the platform has become everyone’s favorite collaboration service. If they would have had to choose one operating system, Slack would’ve lost a huge chunk of its audience and would never have arrived at its current peak.

What’s Best For You?

So who comes out as a winner in cross-platform vs native vs hybrid app development? When comparing the three options, there are still advantages and challenges to overcome for each specific development approach. Choosing the right one for you is determined by the talent you have available, the budget, and the time constraints.

Flutter — An Innovative App Building Approach

Flutter is Google’s open-source technology that enables the use of a single codebase for the creation of native Android and iOS apps. Rather than being a framework, it is a complete SDK (software development kit) that contains everything you require for cross-platform mobile app development.

Flutter is the only cross-platform framework that provides reactive views without requiring JavaScript Bridge. Moreover, flutter has been enormously popular with its impeccable User Experience with a sea full of flutter-based apps out there. One of the major use cases of Flutter is Google’s Adword app. A few other examples are Alibaba, a Chinese multinational E-commerce giant, Reflectly, Watermaniac, Tencent, Birch, and many more.

Some Amazing Stats About Flutter

According to Google Trends, Flutter is the second most leading language, followed by React Native for developing cross-platform mobile apps in 2020.

Source: https://trends.google.com/trends/explore?cat=31&date=all&q=React%20Native,Flutter,NativeScript,Xamarin

According to a Stackoverflow survey, Flutter is the third most loved frameworks, libraries and tools followed by .Net Core and Torch.

Source: https://insights.stackoverflow.com/survey/2019#technology-_-most-loved-dreaded-and-wanted-other-frameworks-libraries-and-tools

From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Team FlutterDevs has been building remarkable mobile apps in Native, Hybrid, and Cross-platform over a decade now. Hire a flutter developer for your mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.

Related: Dialog Using GetX in Flutter

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.

Multi-Language Translator In Flutter

Flutter is well known for its compatibility among other mobile development platforms that why it is one of the most readily growing platforms, and the main reason behind it is the Flutter has come up with every feature and functionality which is required to develop a fully-fledged app. As you know an app is called best app if the user of it does need to access another resource to get its task done and flutter is here to meet all parameters

In this article, we are going to discuss a small technique for Multilanguage translation there are different packages available in the pub.dev and we are going to discuss one of them.

We would implement a technique for translator using this package :

translator | Dart Package
Free Google Translate API for Dart See it in pub: https://pub.dartlang.org/packages/translator and GitHub…pub.dev

You may be in the dilemma that if there is a localization available then why we need to use another package for language translation so the answer is

A free and unlimited Google Translate API for Dart.

You can use it for translate strings and text for educational purpose.

if you need to change a small no of things then it is best to do so instead of using a heavy localization package.

Implementation

First, we need to add this package in pubspec.yaml file.

translator:

then you need to import in the file you are writing your code

import ‘package:translator/translator.dart’;

then you need to create an instance of it

GoogleTranslator translator = GoogleTranslator();

now we need to understand how can we translate our input, Using translate method passing the args from and to designates the language from the text you’re typing and the language to be translated

translator.translate("I love Brazil!", from: 'en', to: 'pt').then((s) {
print(s);
});

or you can omit from language and it’ll auto-detect the language of the source text

translator.translate("Hello", to: 'es').then(print);

also, pass the value to a var using await

var translation = await translator.translate("I would buy a car, if I had money.", from: 'en', to: 'it');
print(translation);
// prints Vorrei comprare una macchina, se avessi i soldi.

The returned value is a Translation an object which holds the translation stuff

var translation = await translator.translate('Translation', from: 'en', to: 'es');
print('${translation.source} (${translation.sourceLanguage}) == ${translation.text} (${translation.targetLanguage})');
// prints Translation (English) == Traducción (Spanish)

You can use the extension method directly on the string too

print(await "example".translate(to: 'pt'));
// prints exemplo

There is a translate and print method that prints directly

translator.translateAndPrint("This means 'testing' in chinese", to: 'zh-cn');
// prints 这意味着用中文'测试
'

now we will use a method to translate given input

here in the given above example, you can see translator.translate is being used to translate the text, it only requires your input and the language in which you want to convert your input.

https://gist.github.com/shivanchalaeologic/a1c44b4957f3a56aaa014b747085efd7#file-multi_lang_translator-dart

As in the above example, you can see that a map of languages is being used to translate every time when the user selects specific language that translator methods execute.

As you can see in this above video it is translating this word in available languages.

Conclusion

This blog is about especially translating things to a small extent as it is best for educational purposes but when it comes to managing the whole app localization is best. However, this package is best if you are required to translate anything quickly on a small scale.


Thanks for reading this article if you find anything that could be improved please let me know, I would love to improve.💙

If this article has helped you a bit and found interesting please clap!👏


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.

Related: Flutter for Multi-Channel Communication

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.

Cache Management in Flutter

0

Introduction

Cache memory is a faster memory storage that stores the data in the memory of the phone locally. It stores the data for a fixed period of time after its data is being cleaned form the memory. We can also use local database techniques such as moor database, SQLite database to store the data but some packages provide us simple methods and functionality to implement cache memory with your app.

In this blog, we will learn how to use cache memory to store the app data, fetch data when needed, delete the data from the memory, delete the entire cache data of the app. Let’s do it…

Demo::


Table of content

  1. Installing dependency
  2. Upload Data in Cache Memory
  3. Fetch data from Cache Memory
  4. Empty cache
  5. Understanding other methods
  6. Github Link

Installing dependency

flutter_cache_manager provides us various methods to perform various operations.

flutter_cache_manager | Flutter Package
A CacheManager to download and cache files in the cache directory of the app. Various settings on how long to keep a…pub.dev

Upload Data in Cache Memory

Initializing file stream

Stream<FileResponse> fileStream = DefaultCacheManager().getFileStream(url);

DefaultCacheManager class provides us getFileStream method to get the stream of the file, it takes the URL to and upload the file inside the cache memory of the device.fileStream returns the stream of FileResponse that stores the information about the file such as file location, time of validity, original URL of the file, source of the file, and file.

Creating a StatelessWidget that returns the stream of FileResponse to display the file

class UploadCacheMemoryData extends StatelessWidget {
@override
Widget build(BuildContext context) {
print("UploadCacheMemoryData");
return StreamBuilder<FileResponse>(
stream: fileStream,
builder: (_, snapshot) {
FileInfo fileInfo = snapshot.data as FileInfo;
return snapshot.hasData
? Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Image.file(fileInfo.file),
Text("Original Url:${fileInfo.originalUrl}"),
Text("Valid Till:${fileInfo.validTill}"),
Text("File address:${fileInfo.file}"),
Text("File source:${fileInfo.source}"),
Text("Hash code:${fileInfo.hashCode}"),
Text("Type:${fileInfo.runtimeType}"),
],
)
: Center(
child: Text("Uploading..."),
);
},
);
}
}
  1. This class returns the stream of FileResponce , builder takes context, and snapshot .snapshot is used to access the file information.
  2. FileInfo fileInfo = snapshot.data as FileInfo; here snapshot data is used FileInfo so that we can access the various methods that provide us information.
  3. For UI we are just displaying the uploaded file on the screen toFileInfo.file provides us the address of the file, to display the file image Image.file() widget is used.

Fetch data from Cache Memory

Initializing the Future

Future<FileInfo> fileInfoFuture = DefaultCacheManager().getFileFromCache(url);

DefaultCacheManager provide us getFileFromCache method to provides the file from the cache memory with the specific URL.

Creating a StatelessWidget that returns the FutureBuilderof FileInfo

DefaultCacheManager().getFileFromCache(url) returns a future that is why we require a FutureBuilder to control fileInfoFuture , the UI part is the same as above.

class FetchCacheMemoryData extends StatelessWidget {
@override
Widget build(BuildContext context) {
print("FetchCacheMemoryData");
return FutureBuilder(
future: fileInfoFuture,
builder: (context, snapshot) {
FileInfo fileInfo = snapshot.data as FileInfo;
return snapshot.hasData
? Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Image.file(fileInfo.file),
Text("Original Url:${fileInfo.originalUrl}"),
Text("Valid Till:${fileInfo.validTill}"),
Text("File address:${fileInfo.file}"),
Text("File source:${fileInfo.source}"),
Text("Hash code:${fileInfo.hashCode}"),
Text("Hash code:${fileInfo.runtimeType}"),
],
)
: Center(child: Text("Fetching..."));
},
);
}
}

Empty cache

DefaultCacheManager provides us emptyCache method delete the entire app cache. In this particular example, we are also setting fileInfoFuture to null . (For better understanding refer full code)

onPressed: () {
DefaultCacheManager().emptyCache();
setState(() {
fileInfoFuture = null;
});
},

Understanding other methods

Refer Usage section

flutter_cache_manager | Flutter Package
A CacheManager to download and cache files in the cache directory of the app. Various settings on how long to keep a…pub.dev

Full code

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

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

class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
actions: [
FlatButton(
onPressed: () {
DefaultCacheManager().emptyCache();
setState(() {
fileInfoFuture = null;
});
},
child: Text("Clear cache"))
],
title: Text("Cache memory demo"),
),
body: fileInfoFuture == null
? UploadCacheMemoryData()
: FetchCacheMemoryData()),
);
}
}

class UploadCacheMemoryData extends StatelessWidget {
@override
Widget build(BuildContext context) {
print("UploadCacheMemoryData");
return StreamBuilder<FileResponse>(
stream: fileStream,
builder: (_, snapshot) {
FileInfo fileInfo = snapshot.data as FileInfo;
return snapshot.hasData
? Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Image.file(fileInfo.file),
Text("Original Url:${fileInfo.originalUrl}"),
Text("Valid Till:${fileInfo.validTill}"),
Text("File address:${fileInfo.file}"),
Text("File source:${fileInfo.source}"),
Text("Hash code:${fileInfo.hashCode}"),
Text("Hash code:${fileInfo.runtimeType}"),
],
)
: Center(
child: Text("Uploading..."),
);
},
);
}
}

class FetchCacheMemoryData extends StatelessWidget {
@override
Widget build(BuildContext context) {
print("FetchCacheMemoryData");
return FutureBuilder(
future: fileInfoFuture,
builder: (context, snapshot) {
FileInfo fileInfo = snapshot.data as FileInfo;
return snapshot.hasData
? Column(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Image.file(fileInfo.file),
Text("Original Url:${fileInfo.originalUrl}"),
Text("Valid Till:${fileInfo.validTill}"),
Text("File address:${fileInfo.file}"),
Text("File source:${fileInfo.source}"),
Text("Hash code:${fileInfo.hashCode}"),
Text("Hash code:${fileInfo.runtimeType}"),
],
)
: Center(child: Text("Fetching..."));
},
);
}
}

Stream<FileResponse> fileStream = DefaultCacheManager().getFileStream(url);
Future<FileInfo> fileInfoFuture = DefaultCacheManager().getFileFromCache(url);
const url = 'https://avatars1.githubusercontent.com/u/41328571?s=280&v=4';

Github Link

flutter-devs/cache_management_demo
A new Flutter application. This project is a starting point for a Flutter application. A few resources to get you…github.com


If you find anything that could be improved please let me know, I would love to improve.💙

If this article has helped you a bit and found interesting please clap!👏


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.

Related: Explore Precache Images In Flutter

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.

The Growth of Flutter Development— 3 Years After The Birth of Alpha

0

The owner of a significant smartphone global market share, China, provides a wide choice of devices for every taste, color, and budget. This significantly makes mobile application technology even more accessible and demanding. Regardless of what your business is — retail, provision of services, or educational activities, today it is next to impossible not to take into account the time that people spend in front of the screens of their mobile devices. That makes the idea of creating the business mobile app for your clients in the coming 2020 year of a great sense.

While there are many ways in which an app can be made using dozens of different technologies and frameworks. And since we all know why cross-platform mobile applications are practically the most suitable for any business.

if not? checkout this article

Native vs Hybrid vs Cross-Platform — What To Choose?
With the constantly gaining enthusiasm towards the development of apps for mobile devices, there has been a myriad of…medium.com

But in this article, we are not going to talk about that. Instead, we’ll talk about the most promising and performing cross-platform mobile development technology — Flutter.

It’s been a little over 3 years when the alpha version of Flutter was released. Since that day, we have seen Flutter as a framework grow into a massive community of millions of people and we will discuss how Flutter became the most loved Framework.

Flutter — A Short Introduction

Flutter is a free and open-source mobile UI framework created by Google and released in May 2017. In a few words, this allows you to create a native mobile application with only one code. It means that you can use one programming language and one codebase to create two different apps (IOS and Android).

Flutter refers to two important things:

  • An SDK (Software Development Kit): A collection of tools that are going to help you to develop your applications. It includes tools to compile your code in native machine code (code for IOS and Android).
  • A Framework (UI Library based on widgets): A collection of reusable UI elements (buttons, text inputs, sliders, etc.) that you can personalize for your personal needs.

To develop with Flutter, you will use a programming language called Dart. It’s also Google’s language created in October 2011 but improved a lot these past years.

Dart focus on front-end development; you can use it to create mobile and web applications.

/media/53767f72df7a0ebd36503a988f06e264

A Brief History of Flutter

Flutter’s beta version was launched on 13th March 2018 and it was first to live on 4th December 2018. In such a short amount of time, Flutter has already established its position in the market. Let’s take a look at the graph below to understand the popularity of Flutter as compared to other mobile platforms.

Now that we know what Flutter is, and why is it so popular among developers and business owners, let’s take a look at some of the greatest apps built with Flutter. People all around the world, have developed thousands of apps with Flutter. It became insanely popular right after it’s alpha launch. Many amazing applications have been build in this framework, but we’ll take a look at the top 6 apps built-in Flutter in the last 3 years.

The Forever Growing Flutter Community

We continue to see fast growth in Flutter usage, with over two million developers having used Flutter in the last 3 years since its release. Despite these unprecedented circumstances, in March there was 10% month-over-month growth, with nearly half a million developers now using Flutter each month.

Some other interesting statistics:

  • 60% of users are developing with Windows, 27% are using macOS, and 13% are using Linux.
  • 35% work for a startup, 26% are enterprise developers, 19% are self-employed, and 7% work for design agencies.
  • 78% of Flutter developers use the stable channel, 11% use beta, and 11% use either dev or master.
  • The top five territories for Flutter are India, China, the United States, the EU, and Brazil.
  • There are approximately 90,000 Flutter apps published in the Play Store, with nearly 10,000 uploaded in the last month alone.

Why is Flutter the best Cross-Platform Technology?

We already know that Flutter is backed by Google and uses Dart programming language. Now, Dart is one of the biggest reasons why developers love Flutter. Dart has Ahead of Time Complied to fast, predictable, native code, which allows Flutter to be written in Dart.

Even though there are a ginormous amount of reasons why Flutter stands out as the best choice for Cross-platform Development, but we’ll try to point out a few. Which are —

High Performance

Flutter allows us to do so much stuff with the apps that are not available on any other platform. Obviously, it will require the framework to be really powerful. In fact, any of the advantages of Flutter wouldn’t be possible without a High-performance cross-platform rendering engine.

Flutter has Skia, their own rendering engine for rendering itself onto the platform provided canvas. Because of this engine UI built in this framework can be launched on virtually any platform.

Lesser Coding

Flutter’s Dart programming language is strongly typed and object-oriented in nature. In Flutter, the programming style is declarative and reactive. Because JavaScript bridge is not necessary for Flutter, the start-up time of the app enhances.

And of course, as Dart programmed flutter framework supports multiple platforms, the written code can be used to support different channels like Mobile, Desktop, and PWA.

Time Tested Efficiency

Flutter has been around enough to showcase concrete proof of its reliance and efficiency. Apps like Google Ads, Reflectly, Alibaba, Hamilton, which we discussed, are the simple portrayal of Flutter’s ridiculous efficiency. These apps with millions of downloads and daily users, generating millions of queries per second, show the reason why these technology giants trusted Flutter with their apps.

Some Amazing Apps Made With Flutter

Flutter Showcase consists of a plethora of applications that are increasing in multiple folds each day with large enterprises trusting flutter for their large userbase apps shows the amount of trust that Flutter offers.

Google Ads (utility) :

Developed by Google using Flutter and it’s available on Android and iOS

Google Ads in an important tool for anyone who is looking to manage and run their ad campaign anywhere on the go. This app helps customers run their ad campaigns so that they can market their services or products and increase their customer base. Featuring a stunning design, this app presents the user with an ocean of information within a tap’s search.

With over 10 Million+ downloads, the app is a beast on its own

Xianyu by Alibaba (eCommerce) :

The Alibaba.com app is a wholesale marketplace for global trade and incorporates Flutter to power parts of the app. The app allows its users to buy products from suppliers around the world, all from the convenience of a mobile app.

Reflectly (Lifestyle):

Reflectly is a personal journal and diary driven by artificial intelligence to enable you to deal with negative thoughts, make positivity louder, and to teach you about the science of well-being. An award-winning mindfulness app built with Flutter. It was featured on the Apple App Store as ‘app of the day’.

Having 1 Million+ downloads with a rating of 4.3 from over 30,000 users.

Birch Finance (Finance):

Birch Finance is a credit card rewards app that helps its users to manage and optimize existing cards. The app enables its users to find the best card for them (according to their spending pattern), tracking spending across all accounts, and offer different ways to earn and redeem rewards.

Hamilton Music (Entertainment):

Flutter empowers the official app of the hit Broadway musical, Hamilton. The app includes exclusive daily news and videos, daily lotteries for New York, Chicago, London, and tour locations, daily trivia game, merchandise store (to purchase items from the official Hamilton store), and more.

Hookle (Social):

Hookle is another app built using Flutter that allows its users to share posts, monitor social activity, and manage multiple social media accounts in one place. Hookle facilitates composing and publishing posts to multiple social media channels, monitor activities across all channels at a glance, customize posts per social media channel, and more.

The Future of Flutter

The increasing rate of adoption of Flutter Framework is telling that more and more mobile developers are switching to Flutter. The continuous effort of the Flutter community to polish the framework is already putting flutter ahead in the race. Over 2 million developers have used Flutter in the last 2 years of its release and it’s constantly growing. In these unprecedented conditions, google saw 10% month over month growth in March, making it nearly a half a million developers using Flutter every month.

With Flutter, the possibilities are practically endless, so even super extensive apps can be created with ease. If you develop mobile apps and have yet to give Flutter a try, I highly recommend you do. After using Flutter since it’s inception, We think its safe to say that it’s the best mobile app development technology and is the future of mobile development. If not, it’s definitely a step in the right direction.

Flutter is a very exciting development in the mobile app space, partly because of Google’s backing, but mainly because of the fresh approach it takes to app development. If you are looking for your app to be free of the shackles of the standard iOS and Android UI elements and you don’t need too many native SDK features, then you are in for a treat as Flutter will give you a great platform for developing fast, great-looking mobile apps.

However, if you are looking for a more conventional-looking mobile app or something that uses more native features, or requires significant 3rd party integrations, then it may be worth waiting a little longer before releasing your company’s first Flutter app.

Our Contribution to the Flutter Community

Flutter was not always the same. We’ve been working on flutter since it’s inception and we’ve seen Flutter and it’s community grow. There were a lot of challenges initially, which were resolved by the community itself.

Like everyone else, we also started from zero. But we’re thrilled to see where we have reached with our dedication and teamwork.

We have bagged 21st Rank worldwide by GitHub awards for our contribution and quality of work. In the last two years of working on Flutter has completely changed the way we see the mobile app development industry. And it never fails to surprise us every day. That is the reason why we as a Mobile App Development Company, majorly develop in Flutter.

Let’s take a look at some of our facts and know where we stand right now:

  • 120+ Open source contribution
  • 10+ Flutter custom Plugins
  • 150+ Blogs
  • 40+ Pre-built Themes
  • More than 25K follower community on social media

Check these links for more Info:


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!

Related: Dark Mode Implementation

Related: Handling Navigation Stacks

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.

Phone Authentication in Flutter

0

Things that you may likely learn from the Blog ::

YOU WILL LEARN HOW TO

  • CONNECT YOUR FLUTTER APP WITH FIREBASE
  • GET THE SHA-1 KEY USING GRADLE METHOD
  • ENABLE PHONE AUTHENTICATION
  • IMPLEMENT THE PHONE AUTHENTICATION FUNCTIONALITY
  • CONTROL UI ACCORDING TO THE AUTH STATE

Demo module::


Importance of phone authentication::

— Images sound more than words —

Introduction

Authenticating the user identity using the users mobile phone number is referred to as Phone Authentication. This verification method is very secure. because when we enter our phone number the phone number is verified in the first step and if the phone number is correct or exists then only the OTP is sent to the respective mobile, after the verification of the OTP only the users are allowed to access the app data.


Table of content

  1. Installing dependencies
  2. Connecting app with firebase & Enabling phone auth
  3. Verifying phone number
  4. Signing in using OTP
  5. SignOut
  6. Managing the UI using the auth state
  7. GitHub Link

Installing Dependencies::

firebase_auth | Flutter Package
A Flutter plugin to use the Firebase Authentication API. For Flutter plugins for other Firebase products, see…pub.dev

Edit your pubspec.yaml

dependencies:
firebase_auth:

Connecting app with firebase & Enabling phone auth::

Please refer to “Setting up the project” section to connect your app with firebase. I have explaned everything in detail.

Using Firebase Firestore in Flutter
Fetching data from cloud firestoremedium.com

GET THE SHA-1 KEY USING GRADLE METHOD

Open Android Studio, go to app-level build.gradle file, click on “Open for editing on Android Studio”, click on Gradle tab, go to

  • android->Tasks->android->singingReport
  • You will get the SHA-1 key in the run Tab.
  • Note: Use this key while adding an app with firebase in the “Register app” section.

Enabling phone auth

  • Go to the Authentication section, go to the phone sign-in Provider, and enable it.
  • You can also add a dummy phone number and OTP for testing purposes.

Verifying phone number::

Firebase auth provides us verifyPhoneNumber() to verify the phone number. FirebaseAuth.instance will create a firebase auth instance that will allow us to access various methods. This method takes six properties phoneNumber, timeout, verificationCompleted, verificationFailed, codeSent, codeAutoRetrievalTimeout .

String phoneNumber, verificationId;
String otp, authStatus = "";

Future<void> verifyPhoneNumber(BuildContext context) async {
await FirebaseAuth.instance.verifyPhoneNumber(
phoneNumber: phoneNumber,
timeout: const Duration(seconds: 15),
verificationCompleted: (AuthCredential authCredential) {
setState(() {
authStatus = "Your account is successfully verified";
});
},
verificationFailed: (AuthException authException) {
setState(() {
authStatus = "Authentication failed";
});
},
codeSent: (String verId, [int forceCodeResent]) {
verificationId = verId;
setState(() {
authStatus = "OTP has been successfully send";
});
otpDialogBox(context).then((value) {});
},
codeAutoRetrievalTimeout: (String verId) {
verificationId = verId;
setState(() {
authStatus = "TIMEOUT";
});
},
);
}

We are also displaying the authStautus if the OTP has been successfully sent it will show OTP has been successfully send , if verification Failed then it will show Authentication failed , if your account verification Completed then Your account is successfully verified will be displayed.

Signing in using OTP::

signIn method

We are using a non-Dismissible AltertDialog Box to enter the OTP. After the OTP is entered the OTP will we used as smsCode in the sign-in process.

Future<void> signIn(String otp) async {
await FirebaseAuth.instance
.signInWithCredential(PhoneAuthProvider.getCredential(
verificationId: verificationId,
smsCode: otp,
));
}

verificationId is the id that we receive while verifying the phone number.

Dialog Box

otpDialogBox(BuildContext context) {
return showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return new AlertDialog(
title: Text('Enter your OTP'),
content: Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
decoration: InputDecoration(
border: new OutlineInputBorder(
borderRadius: const BorderRadius.all(
const Radius.circular(30),
),
),
),
onChanged: (value) {
otp = value;
},
),
),
contentPadding: EdgeInsets.all(10.0),
actions: <Widget>[
FlatButton(
onPressed: () {
Navigator.of(context).pop();
signIn(otp);
},
child: Text(
'Submit',
),
),
],
);
});
}

SignOut::

FirebaseAuth.instance provides us signOut() method to signOut the current user.

Future<void> _logout() async {
try {
await FirebaseAuth.instance.signOut();
} catch (e) {
print(e.toString());
}
}

HomePage.dart

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

class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}

class _HomePageState extends State<HomePage> {
Future<void> _logout() async {
try {
await FirebaseAuth.instance.signOut();
} catch (e) {
print(e.toString());
}
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text("Phone Auth Demo"),
backgroundColor: Colors.cyan,
),
body: FutureBuilder(
future: FirebaseAuth.instance.currentUser(),
builder: (context, snapshot) {
FirebaseUser firebaseUser = snapshot.data;
return snapshot.hasData
? Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Text(
"SignIn Success 😊",
style: TextStyle(
color: Colors.green,
fontWeight: FontWeight.bold,
fontSize: 30,
),
),
SizedBox(
height: 20,
),
Text("UserId: ${firebaseUser.uid}"),
SizedBox(
height: 20,
),
Text(
"Registered Phone Number: ${firebaseUser.phoneNumber}"),
SizedBox(
height: 20,
),
RaisedButton(
onPressed: _logout,
child: Text(
"LogOut",
style: TextStyle(color: Colors.white),
),
color: Colors.cyan,
)
],
),
)
: CircularProgressIndicator();
},
),
);
}
}

LoginPage.dart

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

import 'dart:async';

class LoginPage extends StatefulWidget {
@override
_LoginPageState createState() => _LoginPageState();
}

class _LoginPageState extends State<LoginPage> {
String phoneNumber, verificationId;
String otp, authStatus = "";

Future<void> verifyPhoneNumber(BuildContext context) async {
await FirebaseAuth.instance.verifyPhoneNumber(
phoneNumber: phoneNumber,
timeout: const Duration(seconds: 15),
verificationCompleted: (AuthCredential authCredential) {
setState(() {
authStatus = "Your account is successfully verified";
});
},
verificationFailed: (AuthException authException) {
setState(() {
authStatus = "Authentication failed";
});
},
codeSent: (String verId, [int forceCodeResent]) {
verificationId = verId;
setState(() {
authStatus = "OTP has been successfully send";
});
otpDialogBox(context).then((value) {});
},
codeAutoRetrievalTimeout: (String verId) {
verificationId = verId;
setState(() {
authStatus = "TIMEOUT";
});
},
);
}

otpDialogBox(BuildContext context) {
return showDialog(
context: context,
barrierDismissible: false,
builder: (BuildContext context) {
return new AlertDialog(
title: Text('Enter your OTP'),
content: Padding(
padding: const EdgeInsets.all(8.0),
child: TextFormField(
decoration: InputDecoration(
border: new OutlineInputBorder(
borderRadius: const BorderRadius.all(
const Radius.circular(30),
),
),
),
onChanged: (value) {
otp = value;
},
),
),
contentPadding: EdgeInsets.all(10.0),
actions: <Widget>[
FlatButton(
onPressed: () {
Navigator.of(context).pop();
signIn(otp);
},
child: Text(
'Submit',
),
),
],
);
});
}

Future<void> signIn(String otp) async {
await FirebaseAuth.instance
.signInWithCredential(PhoneAuthProvider.getCredential(
verificationId: verificationId,
smsCode: otp,
));
}

@override
Widget build(BuildContext context) {
return Scaffold(
body: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
SizedBox(
height: MediaQuery.of(context).size.height * 0.2,
),
Text(
"Phone Auth demo📱",
style: TextStyle(
color: Colors.cyan,
fontSize: 30,
fontWeight: FontWeight.bold,
),
),
Image.network(
"https://avatars1.githubusercontent.com/u/41328571?s=280&v=4",
height: 150,
),
Padding(
padding: const EdgeInsets.all(16.0),
child: TextField(
keyboardType: TextInputType.phone,
decoration: new InputDecoration(
border: new OutlineInputBorder(
borderRadius: const BorderRadius.all(
const Radius.circular(30),
),
),
filled: true,
prefixIcon: Icon(
Icons.phone_iphone,
color: Colors.cyan,
),
hintStyle: new TextStyle(color: Colors.grey[800]),
hintText: "Enter Your Phone Number...",
fillColor: Colors.white70),
onChanged: (value) {
phoneNumber = value;
},
),
),
SizedBox(
height: 10.0,
),
RaisedButton(
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30)),
onPressed: () =>
phoneNumber == null ? null : verifyPhoneNumber(context),
child: Text(
"Generate OTP",
style: TextStyle(color: Colors.white),
),
elevation: 7.0,
color: Colors.cyan,
),
SizedBox(
height: 20,
),
Text("Need Help?"),
SizedBox(
height: 20,
),
Text(
"Please enter the phone number followed by country code",
style: TextStyle(color: Colors.green),
),
SizedBox(
height: 20,
),
Text(
authStatus == "" ? "" : authStatus,
style: TextStyle(
color: authStatus.contains("fail") ||
authStatus.contains("TIMEOUT")
? Colors.red
: Colors.green),
)
],
),
),
);
}
}

Managing the UI using the auth state::

FirebaseAuth.instance.onAuthStateChanged provides us the stream of authState. To manage the UI according to the auth state we can use StreamBuilder .

main.dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:phone_auth_example/homePage.dart';
import 'signUpPage.dart';

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

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: StreamBuilder(
stream: FirebaseAuth.instance.onAuthStateChanged,
builder: (ctx, userSnapshot) {
if (userSnapshot.hasData) {
return HomePage();
} else if (userSnapshot.hasError) {
return CircularProgressIndicator();
}
return LoginPage();
},
));
}
}

GitHub Link::

flutter-devs/phone_auth_example
A new Flutter application. This project is a starting point for a Flutter application. A few resources to get you…github.com


Who is this course for?

Want to build Flutter apps with native functionalities?

  1. Want to learn advanced Flutter functionality?
  2. Want to learn job-oriented and high-demand, high-paying flutter iOS and android functionality?

What does this course offer?

  1. Flutter Razorpay payment gateway integration: In this module, we shall learn about Razorpay payment gateway integration which will help us to process the payment of the purchases made by the user.
  2. Flutter Stripe payment gateway integration: In this module, we shall learn about Stripe payment gateway integration which will help us to process the payment of the purchases made by the user.
  3. FLUTTER SCAN AND GENERATE QR CODE: In this module, we shall learn how we can scan a QR code and generate the QR code in Flutter.
  4. FLUTTER FIREBASE EMAIL PASSWORD AUTHENTICATION: In this module, we will learn how we can perform authentication using an email password provider, we will also learn how we can verify the user’s email and reset the password.
  5. FLUTTER FIREBASE PHONE AUTHENTICATION: In this module, we will learn how we can perform authentication using a phone authentication provider, and we will see how we can send the OTP to the provided phone number and sign in using the phone credentials.
  6. FLUTTER FIREBASE GOOGLE AUTHENTICATION: In this module, we will learn how to perform authentication using the google authentication provider using firebase in flutter.

From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.

Thank you for reading. 🌸

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.

Tracking Screen Transition By Route Observer Flutter

0

In this article, We are going to discuss how to observe screen transition in Flutter. As you know Flutter’s widgets do not have any handler methods to handle events related to screen-transitions because widgets do know if they are a part of the screen or whole.

As you know in the flutter navigation is handled by Navigator and is also responsible for screen transitions. There are different options like push, pop screens, and the list of NavigatorObserver can also be passed to Navigator to receive events related to screen-transitions.

A custom NavigatorObserver can also be used but if the handling of it in the state is required then it is a better option to go with the RouteObserver.

What is RouteObserver ?

RouteObeserver is a Navigator observer that notifies RouteAwares of changes to the state of their Route.

A quote from a RouteObserver class to make Its Intention clear.

RouteObserver informs subscribers whenever a route of type R is pushed on top of their own route of type R or popped from it. This is for example useful to keep track of page transitions, e.g. a RouteObserver<PageRoute> will inform subscribed RouteAwares whenever the user navigates away from the current page route to another page route.

Its implementation is quite simple and handy also works very well but when it comes to such an application with various screens it becomes quite huge.

Now let’s understand its working where we would learn its functioning and also get to know how to set different screen transitions in the app as a bonus.

There are two ways to do this as in flutter there are two classes RouteAware and RouteObserver. At first, we would go with RouteAware class.

RouteAware

So lets first understand how does this work and functionalities it possess :

https://gist.github.com/shivanchalaeologic/cf732cc93dd98046c431e928c0bf135b#file-route_aware-dart

As you can understand by reading the above code snippet it is an interface of an object that notifies the current route during transitions and consists of four methods didPopNext(), didPush(),didPop() and didPushNext() these are called at different scenarios as you can read in the code.

Now let’s add this into our code. For this first, we create an instance of RouteObserver then mention all pages where we want to navigate and in navigatorObservers we provide that instance of RouteObserver

https://gist.github.com/shivanchalaeologic/fdf3dd6a084dbc4727343f35792effff#file-main-dart

After that, we move to that RouteAware class from where we will get to know about all the page transitions which are going to take place by using RouteAware() Widget. and get this kind of info :

But for this result like this, we need to implement those four methods mentioned in route_aware.dart. You can implement these methods in every class like this :

https://gist.github.com/shivanchalaeologic/a4ae57023337415312eebc6f79988de3#file-page_two-dart

But writing this boilerplate in every file is not good, So we will make a separate class for this and you will get that expected result.

https://gist.github.com/shivanchalaeologic/c6dce39ba4eb8a46ca819806e113fdd6#file-route_aware-dart

RouteObserver :

RouteObserver is a class that informs user or subscriber if a user navigates to another screen or a route of type “R” is pressed as you can understand easily by reading comments in this official code snippet.

https://gist.github.com/shivanchalaeologic/447fd6290fbb9d4e3d7970853c6cf4ff#file-route_observer-dart

Let’s understand how to use RouteObserver in our app,

The only thing you need to do is by extending RouteObserver you can use those four methods according to your need mentioned in route_aware.dart class.

https://gist.github.com/shivanchalaeologic/3ded41042244c9b1c714863a9b8d3367#file-rout_observer_example-dart

After that, You need to call this class in main.dart & It will automatically notify all the screen transitions.

https://gist.github.com/shivanchalaeologic/24ed18f08f0f14fffbcfaedbd432ef97#file-main-dart

Conclusion

When you are making large scale projects it is necessary to observe transitions meticulously to rectify code compile time its responsiveness then it becomes must because as a developer you get to know about how your app is responding in different scenarios. So as a solution these two techniques are available here to help you out.


Thanks for reading this article if you find anything that could be improved please let me know, I would love to improve.💙

If this article has helped you a bit and found interesting please clap!👏


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.

Dart Extensions Methods

0

As you all know dart is client optimized programming language for multiple platforms and that special term client optimized always indicates that Dart will always come with more suitable and optimized techniques to make developers work with ease. the same thing happened during the announcement of Dart 2.6 when extensions were introduced however that was for a preview but it was finally released in 2.7. Basically extensions feature is the way to add functionality to existing libraries.

If we understand extension methods by a scenario then it would be like

When you’re using someone else’s API or when you implement a library that’s widely used, it’s often impractical or impossible to change the API. But you might still want to add some functionality.

then the most probable solution for that is by writing wrapper classes with static methods and members and it could cause an increase of the number of objects and then extensions feature come in to play.

Sometimes you might get confused in order to clarify the difference between wrapper and extensions so for your information

In Wrapper classes object is passed explicitly to the static methods while in extensions it is extended implicitly.

So this was basic introduction now let’s clarify a few things about extensions

  • How can we use extensions
  • where it is suitable to use and where we should refrain from it

Implementation

Before going over implementation of the extension the first thing which you need to pay attention to is the Dart SDK version. This should be ≥ 3.3, inside your pubspec.yaml

environment:sdk: ">=3.3.0 <4.0.0"

The syntax for the actual implementation

extension <extension_name> on <type> {
(<member_definition>)*
}

Example

Let’s understand it by example, suppose if you are getting data from any third-party API and you are getting value in Celsius but need to show it in Farhenheit, what would you do ??

Simple you would convert it like this

Extension Methods

void main() {

double tempCelsius = 20.0;
double tempFarhenheit = tempCelsius* 1.8 + 32;
// celsiusToFarhenheit();
print('${tempCelsius}C = ${tempFarhenheit}F');

}

but what if you need show throughout in your application then you can do this everywhere but there would be a lot of boilerplate code so here extensions come in because you don’t need to call extensions methods by its name

and the implementation will be like

void main() {

double tempCelsius = 20.0;
double tempFarhenheit = tempCelsius.celsiusToFarhenheit();
print('${tempCelsius}C = ${tempFarhenheit}F');

}
extension on double {
double celsiusToFarhenheit() => this * 1.8 + 32;
}

In this example, we have understood three things

  • It leverages the type system
  • makes our code much easier to understand
  • avoids overloading generic numeric types such as double, with domain-specific logic for temperature conversion.

Extension Operators

void main() {

List prices = [2, 5, 6.75];

print("\nPrice listing after doubling the value");

print(prices ^ 2);
}

extension<T> on List<T> {

List<num> operator ^(int n) =>
this.map((item) => num.parse("${item}") * n).toList();

}

In this example, you can see how we are doubling the values of the list by using extension methods and the output will be

Price listing after doubling the value [4, 10, 13.5]

That was Dart portion, now let’s understand with Flutter

Suppose you are designing UI of app and there are numerous circular Cards where you need to define its shape everywhere so you need to call that circular property everywhere then again we would write the extension method for this see in the example

import 'package:flutter/material.dart';
import 'package:flutter_route_obser/extension_method.dart';

class PageOne extends StatefulWidget {
@override
_PageOneState createState() => _PageOneState();
}

class _PageOneState extends State<PageOne> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: Center(
child: Card(
color: Colors.green,
shape: ShapeBorderX.roundedRectangle(50),
child: Container(
height: 50,
width: 50,
),
),
),
);
}
}

for the extension methods, we make a separate class where all different extensions are described and we only need to call them.in this example, you can see that we are calling shape from the extension method

import 'package:flutter/material.dart';

extension ShapeBorderX on ShapeBorder {
static ShapeBorder roundedRectangle(double radius) {
return RoundedRectangleBorder(
borderRadius: BorderRadius.all(
Radius.circular(radius),
),
);
}
}

extension WidgetPaddingX on Widget {
Widget paddingAll(double padding) => Padding(
padding: EdgeInsets.all(padding),
child: this,
);
}

extension methods are defined by using extension keyword after that we will be able to call all methods without creating any instance variables.

Conclusion

In conclusion, we found that as a developer we have also options to get rid off of a lot of boilerplate and it helps to use the property of any method without creating any instance variables which a big boon when it comes to using any method from different classes.


Thanks for reading this article if you find anything that could be improved please let me know, I would love to improve.💙

If this article has helped you a bit and found interesting please clap!👏


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.

Related: Explore Dart String Interpolation

Related: Metadata Annotations in Dart

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.

What is Agile Methodology in Mobile App Development

0

Agile Methodology is one of the most commonly used practices in project management in current times. The benefits that the method provides such as increased business value, faster go to market, greater transparency among the team, and better quality management is enough to push a number of businesses across a range of industries to follow the Agile approach in their everyday work process.

If your business, seeing the benefits that the methodology has to offer, is also planning to take the agile scrum development route, this article is for you.

Agile Method In the context of Mobile App Development

Holistically, the role of Agile in mobile apps is well-renowned and Scrum is the most commonly used subdomain of the agile methodology, which has quickly expanded to handling big, complicated projects that might have otherwise taken a lot of time to finish.

Mobile application development and keeping it updated in the current scenario is quite a complex process. Even more complex is the task of getting it downloaded on the user’s devices, and used frequently. It is because of a large number of apps available in the marketplace. While a majority of users use the smartphone, it is quite easy to get noticed, but it becomes quite challenging to get the user’s attention as in this gigantic sea of options available for them. Hence it becomes quite necessary for the business owners to design the best app in a short span of time and keep their apps updated as per the latest trends.

Before getting into the details about the Agile methodology of mobile app development, it is necessary to have a brief idea of Agile technology.

What Exactly is Agile?

Agile is an iterative and step-by-step software development methodology. Agile application development helps organize designing and planning methods, development, and testing methods during a software lifecycle. All methods of Agile are based on the following principles:

  • quick response to any changes with the help of adaptive planning.
  • joint elaboration of requirements.
  • rationalization of tasks performed by the development team
  • step-by-step software development with strict time frames.

How Does Agile Work?

Since the Agile app development methodology consists of a few short cycles (2–3 weeks each), there is risk minimization. A customer can see the result after each cycle, and he/she can request to make any changes. Thus, a customer has a direct influence on the development and he/she controls it. Each Agile application development lifecycle includes the following stages:

  • Requirement analysis
  • Design
  • Development
  • Testing
  • Deploy
  • Review

One cycle isn’t enough for building a full-fledged product, but each iteration shows part of the functionality that can be tested and/or changed. After each cycle, the development team sums everything up and can receive new requirements, then some adjustments can be made in the software development plan.

Why is Agile Methodology Good For Mobile App Development?

Now let’s speak about the application of Agile in mobile app development and why use Agile methodology. What particularities do mobile apps have? Unlike conventional desktop applications for PC that may function for a few years without an upgrade, mobile apps should be much more flexible for users. Users’ demands may change rather often, so app owners should update this app every time when it requires new changes. And what is the way to create a high-quality mobile app without additional revisions? Agile methodology is the option.

In-Depth Planning in Real-Time Mode

It can be rather difficult to prepare a plan for the whole development process. Using Agile methodology for mobile application app development, we can prepare a plan for each cycle separately, we don’t waste extra time and resources to fix any bugs since everything can be fixed after each stage of implemented functionality. So we can make a proper plan for each stage without any problems, and it will help us create a first-rate product. By the way, if you should also know how to arrange budget planning for your software project.

Sprint by Sprint

With the help of Agile, we create the software sprint by sprint, as we indicated before. We call each cycle as sprint since it is similar to run on a short distance. We don’t aim to complete the project as quickly as possible, we test and check functionality after each sprint to see whether it works properly or not. Besides that, with Agile we can keep up with more strict deadlines.

Quick Changes

Due to the Agile methodology in mobile application development, it is very convenient to make changes in the app since it is divided into sprints. Thus, it will not have a negative impact on the development process, and changes can be made quickly. Because when the project is almost finished and some serious problems arise, revision can take much more time and money, so Agile methodology helps avoid such situations.

Efficient Risk Management

Users won’t use an app that doesn’t function properly or it has many bugs. It will lead to a total failure of the app. That is why an app can be released step by step with Agile methodology, in the beta version first, to make it possible for users to assess an app and notify about any bugs if they find it. On the basis of it, developers can make all changes quickly, and all risks can be managed timely. Existing bugs will be detected as early as possible. You can see how we organize risk management when we create your app.

Complete Transparency

It is not an acceptable situation when a customer sees a result of the development in the end. If something doesn’t meet expectations of a customer, it will be more difficult to revise the app, it will lead to additional costs and time, and, as a result, to negative feedback from a customer. Agile methodology allows the development team to be always in touch with a customer, provide him/her with an app when each sprint is completed, and if we need to make any changes — we do it quickly without damaging development processes.

So, you can see the main benefits Agile mobile app development methodology brings for mobile app development. Now, let’s move to the most popular framework of Agile.

Benefits of Agile Over Traditional Project management Method

Many developers and project managers prefer to use the agile methodology for a variety of reasons. Some of them are discussed below:

More flexibility

When it comes to making changes in the product or a process, agile methodology is much more flexible than the waterfall methodology. While working, if team members feel that there is a need to experiment and try something different than as planned, the agile methodology easily allows them to do so. The best thing about this methodology is that it focuses more on the product than following a rigid structure.

Unlike the traditional approach, agile methodology isn’t linear or follows a top-down approach. So, any last-minute changes can be accommodated in the process without affecting the end-result and disrupting the project schedule.

Transparency

In agile methodology, everything is out there and transparent. The clients and decision-makers are actively involved in the initiation, planning, review, and testing part of a product. Whereas in the traditional approach, the project manager is holding reins of the project, thus others don’t get to make the major decisions.

Ownership and accountability

In traditional project management, a project manager is the person of the ship which means that the entire ownership belongs to him/her. Customers are also involved during the planning phase but their involvement ends there and then as soon as the execution starts.

In the agile methodology, every team member shares ownership of the project. Each one of them plays an active role to complete the sprint within the estimated time. Unlike traditional project management, everyone involved in the project can easily see view the progress from the beginning to an end.

Scope For Feedback

In the traditional approach, every single process is clearly defined and planned from the beginning of the project. The project has to be completed within the estimated time and budget. So, any big change or feedback that might push the deadline is skipped. Whereas agile management allows constant feedback that is helpful in providing better output.

Scrum

Scrum is another prevalent agile methodology process that implements flexible process control for complex software projects. It also makes use of iterative and incremental practices. Based on the hypothesis that we cannot define the final requirements of the project, in the beginning, the knowledge is gained over the due process from the mistakes made over time. It solely focuses on checking the progress of the project and resolve the difficulties as soon as it is encountered in frequent meetings. It provides the advantage that it helps to take action as and when the requirement changes.

Scrum approach divides the working process into equal sprints — their duration may vary, everything depends on the specific project. Before we start a sprint, it is necessary to draw up tasks for this sprint. When it is completed, all results are discussed. This method makes it possible to lower development costs and make the management process more efficient.

Scrum Development: Responsibility Participants

The techniques of Scrum has become very popular and now considered to be the most important thing to do before starting any project. That is why the demand of the scrum masters and other professions related to the scrum has also increased, and people now are searching about the term scrum more.

The scrum is a very specific and précised framework that is why it comprised of the following roles.

  • Scrum Master
  • Product Owner
  • Scrum Team
  • Stakeholders

Scrum Master is someone who is responsible for solving any sort of problem that the team is facing while building the product. It is not necessary for him to completely understand the requirements; he must be capable enough to find solutions to situations. He has to create and maintain the best possible working condition for the team members so that they can meet the goals of each sprint effectively.

Product Owner is the one who shares the vision of the project (or the product to be developed), prioritizes the functionalities to be built and makes key decisions on behalf of the team or the project. While during project execution, the product owner is the one who is responsible for maintaining the product backlog, bridging the gap between the developers and other stakeholders, managing the end-user (or customer) expectations, and managing the budget (ROI). He is also the one who takes a call on the quality of the product and if it requires any improvement.

A Scrum Team is cross-functional team that is responsible for developing the product. It is a small team consisting of developers, business analysts, testers, etc. The team works together and in tandem while building the application. The activities of each of the team members are aligned in a way such that the targets associated with a specific sprint are achieved. Team members are also responsible for identifying the complexity of the tasks (assigned to them) and allocating efforts (in a number of hours/days) to those.

Conclusion

The agile application development process bears a lot of advantages both for the development team and for customers. We can affirm it as we are highly experienced in it. The methodology makes it possible to build a mobile app that will be accepted by the public with admiration. The only thing you need is a high-skilled software development team that will turn your ideas into reality.


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

Feel free to connect with us:
And read more articles from FlutterDevs.com

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Team FlutterDevs has been building remarkable mobile apps in Native, Hybrid, and Cross-platform over a decade now. Hire a flutter developer for your mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.

Flutter Performance Optimization

Ever wondered how flutter handles all your UI building and events like Futures, taps, etc.. on a single thread( yes it does all that on a single thread 😮😮😮 until and unless explicitly done).

What is Thread/Isolates ?

Thread is an independent process that has its own chunk of memory and executes the given instructions on that memory , It can work parallelly with other threads hence can reduce execution time of multiple process on a single thread .

Let’s understand this with an example :

In Fps games like counter strike, Call of duty, etc. you can see that as soon as you fire a weapon few tasks executes simultaneously like playing of bullet sound, change of bullet count and reduction in opponent health , All these things happens parallelly these are basically threads which execute parallelly and execute their task on separate isolates(isolates and threads can be used interchangeably as isolate is a Dart way of multi threading more on that below) which have its own memory.

Languages like JAVA and C++ Share Their heap memory with threads, but in case of flutter, every isolate has its own memory and works independently. As it has its own private space this memory doesn’t require locking, as if a thread finishes its task it already means that the thread has finished utilizing its memory space and then that memory can go for garbage collection.

To maintain these benefits flutter has a separate memory for every isolate(Flutter way of multi-threading) that’s why they are called isolate 🙂.

Learn more about isolates below.

How can it be helpful to me and where should I use isolates/Threads?

When to use isolates/threads ?

There are a few situations where isolates can be very handy.

  1. Let say you want to execute a network call and you want to process that data that you just received . and that data contains about million records that alone will hang your UI.
  2. You have some image processing tasks that you want to do on-device these kinds of tasks are highly computational as they have to deal with lots of number crunching operations which may lead to frozen UI or legginess in UI.

So to conclude when to use isolates, We should use them whenever you think there is a lot of computation that needs to be offloaded from the main thread.

How to use isolates ?

Flutter team has designed a very elegant and abstract way of using isolates/threads in a flutter, Using compute we can do the same task which isolates does but in a more cleaner and abstract way. Let’s take a look at the flutter compute function.

Syntax:

var getData = await compute(function,parameter);

Compute function takes two parameters :

  1. A future or a function but that must be static (as in dart threads does not share memory so they are class level members not object level).
  2. Argument to pass into the function, To send multiple arguments you can pass it as a map(as it only supports single argument).

compute function returns a Future which if you want can store into a variable and can provide it into a future builder.

Let’s start by analyzing a sample problem:

/media/247dce48c8ac87e5b91b48cd11740086

In the above code pausefunction() is called just below the build method which pauses the execution of code for 10 seconds. And because of that when you try to navigate to this page from a previous one there will be a delay of ten seconds before our page gets pushed on to the widget tree.

We can try to resolve this issue by using async.

https://gist.github.com/702x/24a798189ac096e688f8301f0e2381f2#file-with10seconddelay-dart

As you can see now we have declared our pause function as async even doing this will not help

As async in dart is basically puts our code in ideal until there is something to compute so it seems to us that dart is executing these on a different thread but actually it’s just waiting for some event to occur in that async function.

More on async below :

https://gist.github.com/702x/b50dba38b3aae2e592bd26e2a94a1da5#file-with10seconddelayasync-dart

Let’s solve the above issue using compute.

In the above code, we basically passed our function in compute() function and that creates a separate isolate to handle the task and our main UI will still run without any delay (check the debug console for response ).

Summary:

  1. Dart is by default executes all its code on a single-threaded.
  2. Every function and every async-await calls work only on the main thread(until and unless specified).
  3. We can create multiple threads using compute( Future function/normal function, argument).
  4. You can use compute for executing network calls, performing number-crunching calculations, image processing, etc.

This is all about compute to learn more about isolates (the underlying architecture of computing function) check out isolate .

Thanks for reading this article.

If you find it interesting Please Clap! and if you found anything wrong please let me know I would appreciate it for your contribution.

Check out full code at FlutterDevs GitHub.


From Our Parent Company Aeologic

Aeologic Technologies is a leading AI-driven digital transformation company in India, helping businesses unlock growth with AI automation, IoT solutions, and custom web & mobile app development. We also specialize in AIDC solutions and technical manpower augmentation, offering end-to-end support from strategy and design to deployment and optimization.

Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.

We welcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.

Related: Improving Scrolling Performance in Flutter: ListView, Slivers & Viewport Optimization

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.