Nowadays, working with a location in the app is very common. Using the Flutter Location plugin, it’s effortless to get the user’s location on Android and iOS devices.
In this article, we’ll show how to get the user’s current location and display the address. We will also implement a demo using the location package.
Sometimes to provide the best possible user experience, you need to know the GPS location of their device. The Location package allows you to obtain the current geographic location of the device and listen for changes. You can use this data to display maps, calculate distances, determine the direction the device is facing, and more!
Setup :
Step 1: Add the dependency
Start by adding the dependency to the pubspec.yml file
dependencies:
location: latest version
Android: all the dependencies are automatically added to your project.
It can be found inside <your-project-root-directory>/ios/Runner/folder
Step 2: To get the user’s location import the library into MyLocation.dart
import 'package:location/location.dart';
Implement Code :
Create variables for storing address and location in the MyLocation.dart class and showing in the google map. On location change, we will display it on the screen.
Future<List<Address>> _getAddress(double lat, double lang) async { final coordinates = new Coordinates(lat, lang); List<Address> add = await Geocoder.local.findAddressesFromCoordinates(coordinates); return add; }
}
Conclusion
In this article, I have explained the locationpackage demo, which you can modify and experiment with according to your own. This little introduction was about to get the user’s current location and display it on the map.
I hope this blog will provide you with sufficient information in trying up to get the user’s current locationin your flutter projects. We will show to get the user location demo program for working location in your flutter applications. So please try it.
❤ ❤ Thanks for reading this article ❤❤
If I got something wrong? Let me know in the comments. I would love to improve.
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 fromFlutterDevs.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! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.
Wewelcome 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.
Asynchronous programming is a crucial aspect of modern software development, allowing applications to perform multiple tasks concurrently without blocking the main thread. In Dart and Flutter, mastering asynchronous programming is essential for handling network requests, file I/O, and user interactions In this blog, we’ll explore the fundamentals of asynchronous programming in Dart and how it applies to Flutter development. We’ll also compare different asynchronous programming techniques, cover advanced techniques, and discuss their pros, cons, and limitations.
Understanding Asynchronous Programming
At its core, asynchronous programming deals with code execution that doesn’t happen sequentially. Unlike synchronous code, which executes line by line, asynchronous code allows tasks to run concurrently, improving performance and responsiveness. In Dart, asynchronous programming revolves around asynchronous functions, futures, and streams.
Asynchronous Functions
async: Marks a function as asynchronous, enabling the use of await inside it.
await: Suspends the execution of an asynchronous function until a Future completes.
Future: Represents a potential value or error that will be available in the future.
FutureOr: A type that represents either a Future or a non-future value.
Stream: A sequence of asynchronous events over time.
Isolate: A lightweight process that runs concurrently with other isolates, enabling true parallelism.
Example: Fetching Data from an API:
Future<void> fetchData() async { try { var response = await http.get('https://jsonplaceholder.typicode.com/posts/1'); if (response.statusCode == 200) { var data = jsonDecode(response.body); print('Data received: $data'); } else { print('Failed to load data'); } } catch (e) { print('Error fetching data: $e'); } }
Advanced Asynchronous Techniques
Beyond the basics, Dart offers advanced techniques for handling asynchronous operations efficiently and effectively:
Futures and Error Handling
Chaining Futures: Chain multiple asynchronous operations usingthen and handle errors with catchError.
Concurrency refers to the ability of a system to execute multiple tasks concurrently without blocking each other. In Dart, concurrency is achieved through asynchronous programming techniques like Futures, Streams, and Isolates.
Pros: Lightweight, easy to implement, suitable for handling asynchronous operations.
Cons: Limited scalability and concurrency compared to isolates, cannot achieve true parallelism.
In the above example, fetchData() is executed asynchronously, allowing the program to continue executing other tasks while waiting for the data to be fetched.
Isolates
Isolates are independent workers that run concurrently with the main program and each other, enabling true parallelism in Dart. Each isolate has its memory heap and runs in its thread, allowing heavy computation tasks to be executed in parallel without blocking the main thread.
Pros: Enables true parallelism, ideal for CPU-bound tasks, improves performance and scalability.
Cons: Higher overhead due to separate memory heaps, requires message passing for communication between isolates.
Example: Using Isolates for Parallel Execution
In this example, we spawn a new isolate using Isolate.spawn() and communicate with it using message passing via SendPort and ReceivePort.
import 'dart:isolate';
void main() async { final receivePort = ReceivePort(); await Isolate.spawn(echo, receivePort.sendPort); final sendPort = await receivePort.first; final message = await sendData(sendPort, 'Hello, Isolate!'); print('Received: $message'); }
Concurrency: Involves executing multiple tasks concurrently within the same thread, often achieved through asynchronous programming techniques like Futures and Streams.
Isolates: Enable true parallelism by running independent workers in separate threads with their own memory heap, allowing heavy computation tasks to be executed in parallel without blocking the main thread.
Comparison of Asynchronous Programming Techniques
Let’s compare different asynchronous programming techniques in Dart based on their strengths, weaknesses, and use cases:
Futures
Pros: Simple and easy to understand, suitable for single asynchronous operations.
Cons: Limited concurrency and scalability, cannot handle multiple tasks concurrently without additional techniques.
Example:
Future<void> fetchData() async { final data = await fetchDataFromAPI(); print('Data: $data'); }
Streams
Pros: Ideal for handling continuous data flow and event-driven programming.
Cons: More complex than Futures, managing subscriptions and cancellations can be challenging.
Example:
Stream<int> counterStream() async* { for (int i = 0; i < 10; i++) { await Future.delayed(Duration(seconds: 1)); yield i; } }
Isolates
Pros: Enables true parallelism and scalability, suitable for CPU-bound and I/O-bound tasks.
Cons: Requires communication overhead between isolates and careful management of shared resources.
Future<String> getUserInput() async { // Simulate a delay to mimic user input await Future.delayed(Duration(seconds: 1)); return 'User input'; }
Conclusion
Asynchronous programming is a powerful tool for building responsive and efficient Dart and Flutter applications. By mastering the fundamentals of asynchronous programming and following best practices, developers can create high-performance applications that provide a seamless user experience. Continue exploring asynchronous programming techniques and experimenting with Dart and Flutter to unlock their full potential.
References:
Dart Language Asynchronous Programming
Flutter Asynchronous Programming
Effective Dart: Asynchronous Programming
Dart Isolates
❤ ❤ Thanks for reading this article ❤❤
If I need to correct something? Let me know in the comments. I would love to improve.
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 fromFlutterDevs.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.
Wewelcome 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.
Today we will take a look at one of the most used widgets when making apps, the- popup menu button widget in Flutter.
So, What are pop up menu’s and what do they look like?
Popup menus are one of the most used widgets whether they be in a phone or a computer, they are used to show some additional options to the user, the most common example of an popup menu would be when you right-click with your mouse and see some additional options of rename, delete, copy, paste.
This is a popup menu button
They were given the name popup cause of how they popup on our screen to show us various options.
Now that we know what and why of popup menu’s lets move on to how they are used in flutter . In flutter, on click of a button you can see some popup menu items, it looks like this
You can execute a different function on the press of a popup menu item as well, and they come with great customizations.
Now moving onto code,
It barely takes a few lines to make a popup menu button in flutter, with the required parameter being itemBuilder which provides us with an index to keep track of our buttons.
This is the simplest code for a popup menu button.
Now lets take a look at what other customization options are there for us, Some of the most common ones that you must have used before when making other things are :
: color — usually there to add color to menu items
: padding — adds some padding for each item
: elevation — used to show elevation
: shape — used to modify how it looks like to give borderRadius and borderSide
: enabled — can set to true or false
These are just the common ones, now lets take a deeper down into some that you might have never used before
initialValue — when you open popup menu, the value you have set as the initial value in the menu items gets highlighted. Be sure to provide value inside the PopupMenuItem to use it.
2. onSelected — a function that gives us with the index of the popup menu item we selected and then executes a function on selection.
Example –
onSelected: (int index) { print('index is $index'); },
3. onCancelled — the function that will be executed when you click outside the area of popup menu items, so suppose you didn’t want to select an item and you tapped somewhere else so that popup menu goes away, this function is executed then.
Example –
onCanceled: () { print('cancelled!'); },
4. Offset — one of the interesting ones, it basically decides offset where it will show us popup menu, if you don’t provide it any value then it by default takes offset.zero, it is useful when you want it show it to specific place, it takes the value of an Offset(dx,dy)
Example –
offset: Offset(0, 400),
So these were some of the most common used ones in PopupMenuButton widget.
You can now go ahead and try them all out, or even treat this blog as your cheat sheet for popup menu buttons.
Thanks for reading, I’ll see you in my next blog
Be sure to hit me up if you need any help implementing it.
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 fromFlutterDevs.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! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.
Wewelcome 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.
Tags are small keywords that contain certain information, which helps to describe something like an item. You must have seen them being used in popular social media apps like instagram, twitter etc.
They further help us by classifying items, suppose we are searching for an image of a person which has certain aspects like the ‘person is smiling’ and ‘it is raining’. We can then use tags like ‘rain’ and ‘smile’ to categorize that picture and find the picture we were looking for, that’s basically how tags work.
Now that you are familiar with tags, lets jump into how we are gonna make them.
For creating them you will need following packages :
flutter_tags: "^0.4.9+1" flutter_typeahead:
flutter_typeahead — helps us by suggesting the word that user is currently trying to type in.
flutter_tags — helps us by creating tags for us, when user selects the suggestion.
Now that we are done with getting the necessary packages, we can start working on the code itself.
So first we need a textfield where we can enter our text and have it show us different results based on the text that we entered.
So we will use TypeAheadField here, this widget is the one provided by flutter_typeahead package and will get us all the different results based on our queries,
It takes 3 main parameters :
onSuggestionSelected — its a function which is executed when we select an item from the list that is being shown to us by our query, an example would be to search for apple in a list of fruits by typing ‘ap’ and then clicking on it.
itemBuilder — its a builder function which takes context and suggestions in it, suggestions are simple guesses from our list shown below the textfield in the form of list based on what user is currently typing.
suggestionsCallback — another function, which expects us to return a List of Strings and gives us a value with which we can sort different suggestions based on what user is typing.
Now that all the main functions are out of the way, lets get to coding part of it.
We are first gonna code the suggestionsCallback function so that we can easily get the items in a list format which contains the text that user is typing.
Here we have created a function which will take list of tags and a String suggestion and on basis of it returns the number of items that contains the suggestion, we have used retainsWhere function of List which basically sorts through the list and retains the ones which match our condition, the condition that I have put in here is that we need to convert each item to lowerCase then convert the suggestion to lowerCase then compare if the list item contains that suggestion, if it does then it will return the modified list.
However, to make it look better I have put in another condition that, only returns the modified list if user has entered 2 or more than 2 words in there so if the list of suggestions is too long it won’t look bad.
Alright now that our suggestionCallback is set lets code in our itemBuilder and onSuggestionSelected as well.
This is the basic code for typeAheadField, you will notice that in the itemBuilder I have made a simple ListTile which has title of suggestion, and in the onSuggestionSelected, I have made a simple function that will add the selected item to my list of tags, for now we can comment this function out and notice how it returns our list on writing something in the field.
Of-course before we do so we need to create a list that this will use so the code for that is below
Alright, now we are set so you can go ahead and try it out.
Flutter tags list
Now that we are done with the typeAheadField and we are getting the list of items, now to make a tag on selecting a particular item from the list .We are gonna make a function that will build tags for us and call it right below our typeAheadField widget,
This function will help us generate tags and will even help us remove them, ignore the remove button function for now we will come back to it later.
So this function will work with selectedTags list that we created earlier which should have no value right now but we will fill it upon selection of an item from the list, this function will return tags with titles from that list and an index which is provided by itemBuilder of Tags widget so we can easily determine which tag was clicked on as well.
Now we move onto coding for adding into the selectedTags list,
We have created this _onSuggestionSelected method that takes a String and based on it first checks if this value exists in the list of our tags then if it exists checks if the value is already present in selectedTags list, if it returns null then we add those items into selectedTags list and remove them from tagsList so that we don’t show an item which is already selected by the user in the list.
we are using firstWhere method here to give us the first matching result.
Alright now we will call this method inside the onSuggestionSelected parameter of TypeAheadField as shown above in the TypeAheadField code and pass it the value, after this, it will start showing our tags to us. As adding is done, now we can work on removing the tag and adding the removed tags value back to our list so let’s create a function for that too!
_onSuggestionRemovedfunction works just like the code from _onSuggestionSelected, it will first check if the value exists in the selectedTags list, if it does exists then we will remove that value from selectedTags list and add it back to our tagsList.
Now we can go ahead and call it inside our remove button parameter of Tag widget like shown before.
Alright so we are more or less done with tag system, but what if, the user wants to create their own tag when they submit ?
Now, we are going to create a function to do just that
This _addSuggestion function will help us achieve user making their own tag, First we will check whether the tag that user is specifying already exists in our tagsList if it does, we then check if it exists inside of our selectedTagsList and only add it to our selectedTagsList if it does not exists in it already.
In the else part that is to say it is not present in our tagsList we then check if it is already present inside our selectedTagsList and only add it to the selectedTagsList if it is not already there.
Now you may be asking, where exactly do we call this function?
Well, there is another property of TypeAheadField which is textFieldConfiguration, it takes the value of TextFIeldConfiguration() inside it.
TextFieldConfiguration allows us to interact normally with the textfield that is to say it contains most of the properties of a textField, so we can easily call our function on, onSubmitted, and then we are done.
User entering a custom tagthe user submitting his custom tag
Here is the code
textFieldConfiguration: TextFieldConfiguration( onSubmitted: (val) { print('runtimetype of val is ${val.runtimeType}'); _addSuggestion(val);
}
and with that, we are completely done with letting the user create their own tags.
If you face any problems while implementing this, let me know I will try my hardest to reply to you ASAP, let us meet again in my next blog, hope to see everyone there.
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 fromFlutterDevs.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! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.
Wewelcome 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.
Flutter promises a fast and smooth app but smoothness is the key to any app when we talk about any app’s performance however speed is also like the icing on the cake but as we all know when both characteristics add up a complete and useful app lands on the ground so here we are going to discuss how to observe and rectify both key factors.
Impact of Performance profiling
profiling of performance helps us out to make a better rich user experience app however any app’s performance does not only depend on a single issue but on raw speed, UI smoothness, fewer janks. It also depends on I/O and network but here we are discussing the efforts that can be made during the development phase. So Profiling helps us out to mark problems while developing and sort them out at the same time.
Use Physical Device and run on Profile or release mode
When you are going to observe how your app is reacting when you use it you need to run it on the physical device and your mode should be profile mode because the emulator is not able to give the same performance as any physical device gives.
Advantages of running app on a physical device:
In Debug mode dart code is compiled “just in time” as the app runs and because of this, it causes JIT compilation jank itself so it slows the app while in profile or release mode code is compiled “Ahead of Time” which means the builds are pre-compiled before they are loaded in the device.
Debug mode enables the additional checks which do not happen in the profile or release mode.
Simulator or emulator does not use the hardware as the physical device uses so sometimes emulator works fast while sometimes slow that may cause dilemma as compare to physical devices.
Devtools A necessity
Devtools is a kind of tool that helps to x-rays your whole app on different aspects such as it helps to study code step by step means debugging, memory allocation like to observe app’s heap, enabling the performance overlay and also allows you to investigate the UI performance of your frame by frame.
its timeline view makes developer enable to keenly observe the app’s timing and performance information basically it consists of three parts
Flutter frame chart
timeline events chart
CPU profiler
Identifying through Performance Overlay
Performance overlay like ECG of a body where you can check every single frame top graph is showing the raster thread and bottom graph showing UI thread. it shows how much time has been spent in each frame if the UI is janky and here you can the reason behind the time spent.
Investigating through Graphs
When you are interpreting the information from the graphs you must understand how it is responding, almost top and bottom graphs show the time spent and frames but are of working is different, white lines across the graph show 16ms increment, and if the graph is going over the horizontal lines you running at less than 60Hz. it only updates when your application paints mean you are working or operating unless it stops moving. Results can be misleading if you are testing the app in debug mode so its better to run on profile mode.
The time required related to passing any frame and how it works and what required to maintain in any flutter app in my blog Improve Rendering performance in Flutter. You can read it.
Understanding through Threads
Working of the flutter depends on different threads and two threads can be observed through the overlay. The first one is the Raster thread and the second one is the UI thread besides these two you don’t get access to any thread but your actions on the UI thread can cause good or bad impacts on other threads. Working of threads is important to understand so let’s have a small look at these threads.
Raster Thread
Raster thread holds Skia and graphic libraries to run it also consists of layer tree and displays it in communication with the graphic processing unit. basically, it runs on the CPU, not on the GPU unit however it is not directly accessible but if it lacks in performance it means there is something appropriate in your dart code.
UI Thread:
In this thread Basically, Dart Virtual Machine is used to execute the Dart Code, your written code is executed by Flutter’s Framework on the app’s behalf. A layer tree is created, a lightweight object containing device-agnostic painting commands, and then it sends the layer tree to the raster thread to be rendered on the device.
Platform thread
This thread can not be seen in performance overlay however this platform’s main thread and is responsible to run Plugin code here.
I/O thread
This thread performs important tasks mainly related to I/O and it blocks either The UI or the raster threads. it also can not be seen in performance overlay.
There are different ways to see the performance overlay and these are
Using the Flutter Inspector
From Command line
Programatically
Using the Flutter inspector it is easy to operate with an overlay widget from the Flutter inspector just simply click the button to operate with it. From the command line is can be used by using the P key, it can also be used programmatically.
Identifying Problems in the GPU graph
some times problems can be caused in rendering in the raster thread however layer tree can easily be constructed and when it happens the GPU graph shows the redline but the UI graph does not. In this case, we need to figure out what causing the code’s functioning slower than expected if you figure out you will find out that it is expensive to run on GPU because some of them calling saveLayer.
If you suspect that the source of the slowness is during an animation, click the Slow Animations button in the Flutter inspector to slow animations down by 5x. If you want more control on the speed, you can also do this programmatically.
SaveLayer method is an expensive method in the Flutter framework you should avoid using it if it is not necessary. If it is not called explicitly but it can be called implicitly so always check when your scene is using saveLayer with the PerformanceOverlayLayer.checkerboardOffscreenLayers switch.
Rendering texture using an image file can be costly because at first the compressed image is fetched from persistent storage then it is decompressed into host memory(GPU memory) and then transferred to the device memory. So it becomes costly when I/O thread works. You can see which images are being cached by enabling the PerformanceOverlayLayer.checkerboardRasterCacheImages switch.
Conclusion
So these are the few techniques by which an App can be profiled, Profiling an app gives you an idea where the app is lacking performance vise. Rendering and painting scenes can easily be maintained while the app is working so these steps are to make the app’s performance and function rich.
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!👏
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 fromFlutterDevs.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.
Wewelcome 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!.
In this blog, you will be going to understand the approach of state management using ‘Providers’.
In this blog, we will learn how to manage app state in a very efficient and easy way without building the whole UIagain. We use providers for an easy approach to using state management. The advantage of providers over thesetstatemethod is that it builds the whole UI again…
Before starting our blog, let us know what topic will be going to cover-up
Before starting first install a provider package in pubsec.yaml file:
FutureProvider:
FutureProvider is just the same as FutureBuilder.FutureProvider listens to the future and then exposes its result to its child and its descendants. You can change your initial data to new data that will be reflected in your UI in the future what data you provide with. The future provider will listen to all your changes and then notifies to Consumer that will be going to build in the future.
Let’s understand the FutureProvider with a simple example :
As you can see in the above code the provider is used which is used to tell the UI to change the state of the code. The FutureProvider is used to tell the code that you have to bring changes in UI in the future. As soon as the greeting button is pressed the state is changed after 4 seconds.
The FutureProvider as soon as the Greeting button is pressed tells the Consumer to change the UI in Future.
ProxyProvider :
ProxyProvider is a provider that combines multiple values from other providers into a new object and then sends the result to the provider. It basically injects the one changed value into another provider. Whenever there is more than one provider used and the value of one provider depends on another provider at that time we use ProxyProvider. The other provider updates its value whenever one of the providers it depends on also updates.
The ProxyProvider comes under multiple variants such as ProxyProvider vs ProxyProvider2 vs ProxyProvider3, …, The digit after the class name signifies the number of other providers it depends on.
Let us understand ProxyProvider with an example:
As you can see from the above code we have used MultiProvider and inside it, we have created two simple providers. The value of one provider depends on another provider so we have used ProxyProvider in it. If you do not know about MultiProvider then no need to worry it is just the same as using Row or Column, where you can create multiple different providers.
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 a 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.
Wewelcome 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!.
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.
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.
5. CallrunOnce 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.
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 fromFlutterDevs.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.
Wewelcome 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.
Flutter is a portable UI toolkit. In other words, it’s a comprehensive app Software Development toolkit (SDK) that comes complete with widgets and tools. Flutter is a free and open-source tool to develop mobile, desktop, web applications. Flutter is a cross-platform development tool. This means that with the same code, we can create both ios and android apps. This is the best way to save time and resources in our entire process. In this, hot reload is gaining traction among mobile developers. Allows us to quickly see the changes implemented in the code with hot reload
In this blog, we will explore the Stack and Positioned Widget In Flutter. We will also implement a demo of thestack and positioned widget, describes its properties, and how to use them in your flutter applications. So let’s get started.
The stack is a widget in Flutter. It contains a list of widgets and places them on top of each other. And it places their children on top of each other like a stack of books. In other words, stack developers would overlap multiple widgets on one screen. As you can add different images or colors using containers in it.
Properties of the Stack Widget:
The following are the basic properties of the stack widget.
alignment: The alignment determines that.How to align children’s widgets in the stack. It can be top,bottom,center,etc.
text direction: The text direction determines the text direction. It can draw the text either ltr (left to right) or rtl (right to the left).
Fit: The fit Property is of type BoxFit.Its use describes how a box is marked in another box. It completes semantics sizing.
The Positioned widgets, as we know by name. This is related to the position of some widgets. The right positioned widgets allow us to control this. A child of that stack is positioned on the inside of the stack.
The following are the parameters of the positioned:
In this demo module video. Stack and Positioned Widget is used, Which overlaps several containers on the screen. And use the positioned widget. And set its positions from left and top.
Code Implementation:
You need to implement it in your code respectively:
Create a new dart file called stack_and_positioned_demo.dart inside the lib folder.
In this stack and positioned widget. We used 3 Containers that we wrap with the stack. All the containers have different colors and names. And the stack has set all its containers vertically.
Now we have wrapped her child inside the stack widget with the positioned widget as we have already understood about the positioned widget. In the positioned widget, we have given its position from the top and left.
In this article, I have explained a Stack & Positioned demo, which you can modify and experiment with according to your own. This little introduction was from the Stack & Positioned widget from our side.
I hope this blog will provide you with sufficient information in Trying up the Stack & Positioned widgetin your flutter project. We will show you the stack & positioned widget is?, show a working demo program of the stack & positioned widget in your flutter applications, So please try it.
If I got something wrong? Let me know in the comments. I would love to improve.
Clap 👏 If this article helps you.
If we got something wrong? Let me know in the comments. We would love to improve.
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 a 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.
Wewelcome 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.
The Flutter Inspector is an unimaginable resource that assists developers with diagnosing configuration issues and various issues in Flutter applications. Flutter relies upon Widgets and Widget Trees. If you are new to Flutter, imagine Widgets as plans of Data or Classes of Data. Likewise, to make a Flutter application we home these Widgets inside one another.
This blog will Explore Layout Inspector In Flutter. We perceive how to execute a demo program. We will show you how to use it in your Flutter applications.
Flutter gives a tool called Flutter Inspector which can assist you with envisioning the blueprint and properties of various widgets in your Flutter Application. Alongside perception, the Inspector apparatus additionally helps in diagnosing Widget design issues.
The Flutter inspector is an amazing asset for envisioning and investigating Flutter widget trees. The Flutter structure involves widgets as the core building block for anything from controls The inspector helps you envision and investigate Flutter widget trees.
Debugging Layout Issues:
Here are some steps to debug layout issues with the Flutter Inspector.
The following is a manual for the elements accessible in the inspector’s toolbar. At the point when space is restricted, the symbol is utilized as the visual adaptation of the label.
> Open the Flutter Inspector — Begin by running your Flutter application in debug mode and opening the Flutter Inspector. You can do this by tapping on the “Open Flutter Inspector” button in your IDE’s toolbar or by composing “flutter inspect” in your terminal.
> Select the widget you want to inspect — Utilize the Flutter Inspector to choose the widget you need to assess by tapping on it in the widget tree. You can then see data about the widget in the Inspector panel, including its size, position, and requirements.
Subsequent to choosing any Widget from the Widget Tree you can see the outline of that Widget with the assistance of the Layout Explorer tab.
You can check various properties and nested widgets of the chosen Widget with the assistance of the Widget Details Tree tab.
> Check the constraints — The requirements of a widget can be a typical reason for design issues. Ensure that the widget has the right requirements and that they are being applied accurately.
> Check the widget’s parent — If a widget isn’t being spread out accurately, it very well might be because its parent isn’t applying the current situation to the right requirements or properties. Utilize the Inspector to investigate the widget’s parent and look at its properties and requirements.
> Refresh Tree — Whenever you make changes in your app, and you hot reload those changes are not immediately reflected in your Flutter Inspector tool. To visualize the changes you will have to click the Refresh Tree button.
> Debug Pain — The “Debug Paint” highlight in the Flutter Inspector can assist you with picturing the design of your widgets. You can empower this component by tapping on the “Switch Debug Paint” button in the Inspector panel.
> Slow Animation — Reduces the speed of animation between layouts.
> Paint BaseLines — It draws baselines for all the texts and icons currently present on the screen. Cause each RenderBox to paint a line at each of its text baselines.
> Repaint Rainbow — Shows rotating colors on layers when repainting. When activated it creates a border around the widgets that are changing. So It’s a great tool to check/debug widgets that are changing.
Steps To Inspect Layout In Flutter:
Debugging layout issues in Flutter can be a difficult undertaking, yet the Flutter Inspector device can be exceptionally useful in recognizing and settling layout issues.
> Start Your App In Debug Mode:
To use the Flutter Inspector, you need to start your app in debug mode. You can do this by running the following command in your terminal:
flutter run –debug
> Open The Flutter Inspector:
Once your application is running in debug mode, you can open the Flutter Inspector by tapping the “Open DevTools” button in the Flutter SDK apparatus. On the other hand, you can likewise open the Flutter Inspector by running the accompanying order in your terminal:
flutter inspect
This will open the Flutter Inspector in your default web browser.
> Inspect The Widget Tree:
When the Flutter Inspector is open, you can utilize it to assess the widget tree of your application. The widget tree is a progressive portrayal of the relative multitude of widgets in your application, and it can assist you with distinguishing design issues. You can explore the widget tree by tapping on the widgets and extending their children.
> Identify Layout Issues:
As you explore the widget tree, search for widgets that are not showing true to form. This might incorporate widgets that are covering, not adjusted as expected, or not taking up the right measure of room. You can likewise utilize the Flutter Inspector to see the design constraints of every widget, which can assist you to recognize issues with the imperatives.
> Fix Layout Issues:
Whenever you have recognized layout issues, you can utilize the Flutter Inspector to try different things with various format imperatives and perceive what they mean for the format of your application. You can likewise alter the code straightforwardly in the Flutter Inspector to make changes to the layout of your application.
> Test Your Changes:
In the wake of making changes to your design, test your application to check whether the issues have been settled. On the off chance that not, keep on utilizing the Flutter Inspector to recognize and fix any excess design issues.
Conclusion:
In the article, I have explained the Explore Layout Inspector In Flutter; you can modify this code according to your choice. This was a small introduction to Explore Layout Inspector 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 the Explore Layout Inspector In Flutter. You can utilize the Flutter Inspector to recognize and determine layout issues in your Flutter application. Make sure to test your progressions completely to guarantee that your application is working as expected. So please try it.
❤ ❤ Thanks for reading this article ❤❤
If I got something wrong? Let me know in the comments. I would love to improve.
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 fromFlutterDevs.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.
Wewelcome 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.
While developing mobile applications, there are so many times when we have to interact with outside of your applications. So to achieve this Flutter provides an easy way by usingurl_launcher package.
In this article, we’ll show how to interact with another application from your app
Flutter is Google’s UI toolkit for building beautiful, natively compiled applications for mobile, web, and desktop from a single codebase. URL launcher is used to open websites, create mail, open maps, etc.
To interact with outsider apps from your app we need to use a URL launcher package.
Setup
Step1: Add the dependency
Start by adding the dependency to the pubspec.yml file
dependencies: url_launcher: latest version
Supported URL schemas
The launch method takes a string argument containing a URL. This URL can be formatted using a number of different URL schemes. The supported URL schemes depend on the underlying platform and installed apps.
Code Implementation:
Create three buttons to launch web URL, mail, and map in the MyHomePage.dart class, and on clicking that button showing the corresponding launch.
For opening the web pages, on click of button Open URL call this method,
For Google map and apple map, pass latitude and longitude in the base url,
Sent an email by specifying the receiver’s email, subject, and body of the mail
In these snippets, we are using url_launcher to open outsider app like email, webpage, and map.
In this article, I have explained URL launcher package demo which you can modify and experiment with according to your own. This little introduction was about to open an outsider app from my app like a map, webpage, and email.
I hope this blog will provide you with sufficient information in trying up to use url_launcher in your flutter projects. We will show this demo program for working url launcher in your flutter applications. So please try it.
❤ ❤ Thanks for reading this article ❤❤
If I got something wrong? Let me know in the comments. I would love to improve.
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 fromFlutterDevs.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! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.
Wewelcome 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.