Sunday, June 23, 2024
Google search engine
HomePerformance and OptimizationAsyncMemoizer In Flutter

AsyncMemoizer In Flutter

Flutter developers, celebrate! AsyncMemoizer is your unmistakable advantage for enhancing application speed and effectiveness. This incredible asset caches the consequences of asynchronous capabilities, guaranteeing smooth performance and negligible asset utilization.

In this article, we will explore the AsyncMemoizer In Flutter. We see how to execute a demo program. We will tell every one of the significant details of this strong helper, explaining its purpose, functionalities, and viable use in your Flutter applications.

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table Of Contents::

What is AsyncMemoizer?

Key Features

Benefits

When to Use

How to Use

Code File

Conclusion



What is AsyncMemoizer?

AsyncMemoizer is a class that assists you with caching the consequences of asynchronous capabilities. It guarantees that the function runs just a single time for a given arrangement of sources of info, regardless of whether it’s called on various occasions. This can fundamentally further develop performance by keeping away from repetitive organization calls or costly computations.

Key Features:

  • Caching: Stores the aftereffect of the primary successful execution for future calls with similar contentions.
  • Thread-safety: Handles simultaneous calls securely, preventing race conditions and unforeseen ways of behaving.
  • Error Handling: Propagates errors from the first function, permitting appropriate reaction to disappointments..
  • Customization: Choices like clearing cache, setting key generation functions, and giving error handlers overseers offer adaptability.

Benefits:

  • Performance Improvement: Lessens repetitive calculations and organization calls, prompting quicker application responsiveness.
  • Efficiency: Limits asset use by keeping away from superfluous work.
  • Maintainability: Works on code by taking care of caching logic internally.

When to Use:

  • API calls with static data: If the API response doesn’t change often, store it to stay away from superfluous network requests.
  • Expensive calculations: Memoize the consequences of perplexing estimations to try not to recalculate them for similar sources of info.
  • Data fetching in widgets: Use it with FutureBuilder or comparative widgets to prevent redundant data fetching on rebuilds.

How to Use:

  1. Import the package:
import 'package:async/async.dart';
import 'package:http/http.dart';
import 'dart:developer';

2. Create a function that makes a network call:

Future<String> fetchDataFromApi() async {
final response = await get(Uri.parse('https://catfact.ninja/fact'));

if (response.statusCode == 200) {
return response.body;
} else {
throw Exception('Failed to load data from API');
}
}

3. Initialise AsyncMemoizer and Stopwatch

final memoizer = AsyncMemoizer<String>();
final stopwatch = Stopwatch()..start();

4. Call runOnce method on AsyncMemoizer that accepts our fetchDataFromApi function

String data1 = await memoizer.runOnce(fetchDataFromApi);

log('data1: $data1',name: 'memoizer'); // Output: cats facts

final firstCallTime = stopwatch.elapsed;

log("First call: $data1 (took ${firstCallTime.inMilliseconds}ms)",name: 'memoizer');

stopwatch.reset();

5. Call runOnce technique on AsyncMemoizer that acknowledges our fetchDataFromApi function and returns as data2

String data2 = await memoizer.runOnce(fetchDataFromApi);

log('data2: $data2',name: 'memoizer'); // Output: Data from API (almost instantaneous)

final secondCallTime = stopwatch.elapsed;

log("Second call: $data2 (took ${secondCallTime.inMilliseconds}ms)",name: 'memoizer');
log('data1 == data2: ${data1 == data2}', name: 'memoizer'); // Output: true

The logs will look something like this:[memoizer] data1: {"fact":"A female cat is called a queen or a molly.","length":42}
[memoizer] First call: {"fact":"A female cat is called a queen or a molly.","length":42} (took 723ms)
[memoizer] data2: {"fact":"A female cat is called a queen or a molly.","length":42}
[memoizer] Second call: {"fact":"A female cat is called a queen or a molly.","length":42} (took 0ms)
[memoizer] data1 == data2: true

Code File:

import 'dart:developer';
import 'package:async/async.dart';
import 'package:http/http.dart';

Future<String> fetchDataFromApi() async {
final response = await get(Uri.parse('https://catfact.ninja/fact'));

if (response.statusCode == 200) {
return response.body;
} else {
throw Exception('Failed to load data from API');
}
}

void main() async {
final memoizer = AsyncMemoizer<String>();

final stopwatch = Stopwatch()..start();

String data1 = await memoizer.runOnce(fetchDataFromApi);
log('data1: $data1',
name: 'memoizer'); // Output: Data from API (takes 2 seconds)

final firstCallTime = stopwatch.elapsed;

log("First call: $data1 (took ${firstCallTime.inMilliseconds}ms)",
name: 'memoizer');

stopwatch.reset();

String data2 = await memoizer.runOnce(fetchDataFromApi);
log('data2: $data2',
name: 'memoizer'); // Output: Data from API (almost instantaneous)

final secondCallTime = stopwatch.elapsed;

log("Second call: $data2 (took ${secondCallTime.inMilliseconds}ms)",
name: 'memoizer');

log('data1 == data2: ${data1 == data2}', name: 'memoizer'); // Output: true
}

Conclusion:

In the article, I have explained the AsyncMemoizer In Flutter; you can modify this code according to your choice. This was a small introduction to the AsyncMemoizer In Flutter User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information on Trying AsyncMemoizer in your Flutter projects. By understanding AsyncMemoizer and its abilities, you can upgrade your Flutter applications by productively storing asynchronous tasks and improving performance. So please try it.


❤ ❤ Thanks for reading this article ❤❤

If I need to correct something? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


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 a Flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.

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 ARTICLES

1 COMMENT

LEAVE A REPLY

Please enter your comment!
Please enter your name here

- Advertisment -
Google search engine

Most Popular

PDF with Flutter

Rest API in Flutter

Charts in Flutter

Spinkit In Flutter

Recent Comments