Google search engine
Home Blog Page 51

Location In Flutter

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.

location | Flutter Package
This plugin for Flutter handles getting location on Android and iOS. It also provides callbacks when location is…pub.dev


Table of Contents :

Introduction

Setup

Code Implementation

Code File

Conclusion


Introduction :

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.

IOS:

Modify the Info.plist file to add the permission

NSLocationWhenInUseUsageDescription
NSLocationAlwaysUsageDescription

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.

LocationData _currentPosition;
String _address,_dateTime;

Now we get the location, In this function, we will get the coordinates of the user

Now we are showing coordinates on the screen.

Get address from the coordinates

Display address and coordinates

Wherever you want to display it on the screen

On Google map,

In these snippets, we are using google map and text to display the user’s coordinates and address.

Code File

import 'dart:async';

import 'package:flutter/material.dart';
import 'package:location/location.dart';
import 'package:geocoder/geocoder.dart';
import 'package:intl/intl.dart';
import 'package:google_maps_flutter/google_maps_flutter.dart';


class MyLocation extends StatefulWidget {
@override
_MyLocationState createState() => _MyLocationState();
}


class _MyLocationState extends State<MyLocation> {
LocationData _currentPosition;
String _address,_dateTime;
GoogleMapController mapController;
Marker marker;
Location location = Location();

GoogleMapController _controller;
LatLng _initialcameraposition = LatLng(0.5937, 0.9629);

@override
void initState() {
// TODO: implement initState
super.initState();
getLoc();

}

void _onMapCreated(GoogleMapController _cntlr)
{
_controller = _controller;
location.onLocationChanged.listen((l) {
_controller.animateCamera(
CameraUpdate.newCameraPosition(
CameraPosition(target: LatLng(l.latitude, l.longitude),zoom: 15),
),
);
});
}

@override
Widget build(BuildContext context) {
return Scaffold(

body: Container(
decoration: BoxDecoration(
image: DecorationImage(
image: AssetImage('assets/images/bg.jpg'), fit: BoxFit.cover),
),
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
child: SafeArea(
child: Container(
color: Colors.blueGrey.withOpacity(.8),
child: Center(
child: Column(
children: [
Container(
height: MediaQuery.of(context).size.height/2.5,
width: MediaQuery.of(context).size.width,
child: GoogleMap(
initialCameraPosition: CameraPosition(target: _initialcameraposition,
zoom: 15),
mapType: MapType.normal,
onMapCreated: _onMapCreated,
myLocationEnabled: true,
),
),
SizedBox(
height: 3,
),
if (_dateTime != null)
Text(
"Date/Time: $_dateTime",
style: TextStyle(
fontSize: 15,
color: Colors.white,
),
),

SizedBox(
height: 3,
),
if (_currentPosition != null)
Text(
"Latitude: ${_currentPosition.latitude}, Longitude: ${_currentPosition.longitude}",
style: TextStyle(
fontSize: 22,
color: Colors.white,
fontWeight: FontWeight.bold),
),
SizedBox(
height: 3,
),
if (_address != null)
Text(
"Address: $_address",
style: TextStyle(
fontSize: 16,
color: Colors.white,
),
),
SizedBox(
height: 3,
),
],
),
),
),
),
),

);
}


getLoc() async{
bool _serviceEnabled;
PermissionStatus _permissionGranted;

_serviceEnabled = await location.serviceEnabled();
if (!_serviceEnabled) {
_serviceEnabled = await location.requestService();
if (!_serviceEnabled) {
return;
}
}

_permissionGranted = await location.hasPermission();
if (_permissionGranted == PermissionStatus.denied) {
_permissionGranted = await location.requestPermission();
if (_permissionGranted != PermissionStatus.granted) {
return;
}
}

_currentPosition = await location.getLocation();
_initialcameraposition = LatLng(_currentPosition.latitude,_currentPosition.longitude);
location.onLocationChanged.listen((LocationData currentLocation) {
print("${currentLocation.longitude} : ${currentLocation.longitude}");
setState(() {
_currentPosition = currentLocation;
_initialcameraposition = LatLng(_currentPosition.latitude,_currentPosition.longitude);

DateTime now = DateTime.now();
_dateTime = DateFormat('EEE d MMM kk:mm:ss ').format(now);
_getAddress(_currentPosition.latitude, _currentPosition.longitude)
.then((value) {
setState(() {
_address = "${value.first.addressLine}";
});
});
});
});
}


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 location package 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 location in 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.

Clap 👏 If this article helps you.


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 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.

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.

Asynchronous In Dart & Flutter

0

In this article, we will explore the Asynchronous In Dart & Flutter. We see how to execute a demo program in your Dart and 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

Introduction 

Understanding Asynchronous Programming

Advanced Asynchronous Techniques

Handling Asynchronous Operations

Concurrency and Isolates

Comparison of Asynchronous Programming Techniques

Best Practices for Asynchronous Programming

Real-World Examples and Use Cases

Conclusion

References


Introduction

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 using then and handle errors with catchError.

Future<void> fetchAndProcessData() {
return fetchDataFromAPI()
.then((data) => processData(data))
.catchError((error) => handleError(error));
}

Timeouts: Implement timeouts for Futures to prevent blocking operations.

Future<void> fetchDataWithTimeout() async {
try {
var data = await fetchDataFromAPI().timeout(Duration(seconds: 5));
print('Data received: $data');
} catch (e) {
print('Operation timed out or failed: $e');
}
}
  • Streams and Reactive Programming

Stream Controllers: Create and manage streams using StreamController to handle continuous data flow.

StreamController<int> streamController = StreamController<int>();

void addDataToStream() {
for (int i = 0; i < 5; i++) {
streamController.add(i);
}
streamController.close();
}

void listenToStream() {
streamController.stream.listen((data) {
print('Data received: $data');
});
}

void main() {
addDataToStream();
listenToStream();
}

Stream Transformers: Use stream transformers for filtering, transforming, and combining stream data.

Stream<int> numberStream = Stream.fromIterable([1, 2, 3, 4, 5]);

Stream<int> transformedStream = numberStream.transform(StreamTransformer.fromHandlers(
handleData: (data, sink) {
sink.add(data * 2);
}
));

transformedStream.listen((data) {
print('Transformed data: $data');
});
  • Isolates and Parallelism

Spawning Isolates: Spawn isolates for parallel execution of CPU-bound and I/O-bound tasks.

import 'dart:isolate';

void isolateFunction(SendPort sendPort) {
int result = 0;
for (int i = 0; i < 1000000000; i++) {
result += i;
}
sendPort.send(result);
}

void main() async {
ReceivePort receivePort = ReceivePort();
await Isolate.spawn(isolateFunction, receivePort.sendPort);
int result = await receivePort.first;
print('Result from isolate: $result');
}

Communication: Exchange messages between isolates using SendPort and ReceivePort.

import 'dart:isolate';

void isolateFunction(List<dynamic> args) {
SendPort sendPort = args[0];
int data = args[1];
int result = data * 2;
sendPort.send(result);
}

void main() async {
ReceivePort receivePort = ReceivePort();
await Isolate.spawn(isolateFunction, [receivePort.sendPort, 10]);
int result = await receivePort.first;
print('Result from isolate: $result');
}

Handling Asynchronous Operations

Working with asynchronous operations in Dart involves proper handling to ensure smooth execution and error management:

  • Use Future for single asynchronous operations and await to wait for their completion.
  • Chain asynchronous operations using then and handle errors with catchError.
  • Wrap asynchronous code in a try-catch block to handle exceptions gracefully.

Example:

Future<void> fetchData() async {
try {
var data = await fetchDataFromServer();
print('Data received: $data');
} catch (e) {
print('Error fetching data: $e');
}
}

Concurrency and Isolates

Concurrency

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.

Example: Concurrent Execution with Futures

void main() {
print('Start');
fetchData().then((data) {
print('Data: $data');
});
print('End');
}

Future<String> fetchData() async {
await Future.delayed(Duration(seconds: 2));
return 'Hello, World!';
}

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');
}

void echo(SendPort sendPort) {
final receivePort = ReceivePort();
sendPort.send(receivePort.sendPort);
receivePort.listen((message) {
sendPort.send(message);
});
}

Future<String> sendData(SendPort sendPort, String message) {
final receivePort = ReceivePort();
sendPort.send([message, receivePort.sendPort]);
return receivePort.first;
}

Difference Between Concurrency and Isolates

  • 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.
  • Example:
Future<void> processDataInIsolate() async {  
final isolate = await Isolate.spawn(doHeavyTask, 'data');
isolate.addErrorListener(...);
isolate.addMessageListener(...);
}

Best Practices for Asynchronous Programming

To write efficient and maintainable asynchronous code, follow these best practices:

  • Avoid Nesting: Refrain from nesting asynchronous operations to maintain code readability.
  • Error Handling: Handle errors and exceptions gracefully to prevent application crashes and unexpected behavior.
  • Cancellation: Use cancellation tokens to cancel long-running operations and free up resources.
  • Performance Optimization: Minimize unnecessary async/await calls and leverage parallelism for improved performance.

Real-World Examples and Use Cases

Let’s explore some real-world scenarios where asynchronous programming is crucial:

  • Network Requests: Fetch data from APIs asynchronously to maintain app responsiveness.
Future<void> fetchNetworkData() async {
try {
var response = await http.get('https://jsonplaceholder.typicode.com/posts');
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');
}
}
  • File I/O: Read and write files asynchronously to prevent blocking the main thread.
import 'dart:io';

Future<void> readFile() async {
try {
var file = File('example.txt');
String contents = await file.readAsString();
print('File contents: $contents');
} catch (e) {
print('Error reading file: $e');
}
}

Future<void> writeFile() async {
try {
var file = File('example.txt');
await file.writeAsString('Hello, Dart!');
print('File written successfully');
} catch (e) {
print('Error writing file: $e');
}
}
  • User Interactions: Handle user inputs and gestures asynchronously to provide a smooth and interactive user experience.
Future<void> handleUserInput() async {
try {
var userInput = await getUserInput();
print('User input received: $userInput');
} catch (e) {
print('Error handling user input: $e');
}
}

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.

Clap 👏 If this article helps you.


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 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.


PopupMenuButton in Flutter

0

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.

PopupMenuButton(
child: Center(child: Text('click here')),
itemBuilder: (context) {
return List.generate(5, (index) {
return PopupMenuItem(
child: Text('button no $index'),
);
});
},
),

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

  1. 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.

Example –

PopupMenuButton(
initialValue: 2,
child: Center(
child: Text('click here')),
itemBuilder: (context) {
return List.generate(5, (index) {
return PopupMenuItem(
value: index,
child: Text('button no $index'),
);
});
},
),

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.


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 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.

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.

Tags In Flutter

What are tags?

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 :

  1. 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.
  2. 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.
  3. 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.

_sugestionList({@required List<String> tags , @required String suggestion}) {
List<String> modifiedList = [];
modifiedList.addAll(tags);
modifiedList.retainWhere((text) => text.toLowerCase().contains(suggestion.toLowerCase()));
if(suggestion.length >=2) {
return modifiedList;
}
else {
return null;
}
}

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.

TypeAheadField(
hideOnLoading: true,
hideOnEmpty: true,
getImmediateSuggestions: false,
onSuggestionSelected: (val) {
_onSuggestionSelected(val);
},
itemBuilder: (context, suggestion) {
return ListTile(
title: Text(suggestion,),
);
},
suggestionsCallback: (val) {
return _sugestionList(tags: tagsList, suggestion: val,);
// return ;
},
),

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

List<String> tagsList = ['apple', 'banana', 'orange', 'kiwi' , ''];
List<String> selectedTags = [];

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,

_generateTags() {
return selectedTags.isEmpty ?
Container()
:
Container(
alignment: Alignment.topLeft,
child: Tags(
alignment: WrapAlignment.center,
itemCount: selectedTags.length,
itemBuilder: (index) {
return ItemTags(
index: index,
title: selectedTags[index],
color: Colors.blue,
activeColor: Colors.red,
onPressed: (Item item) {
print('pressed');
},
highlightColor: Colors.transparent,
splashColor: Colors.transparent,
elevation: 0.0,
borderRadius: BorderRadius.all(Radius.circular(7.0)),
// textColor: ,
textColor: Colors.white,
textActiveColor: Colors.white,
removeButton: ItemTagsRemoveButton(
color: Colors.black,
backgroundColor: Colors.transparent,
size: 14,
onRemoved: () {
_onSuggestionRemoved(selectedTags[index]);
return true;
}),
textOverflow: TextOverflow.ellipsis,
);
},
),
);
}

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,

_onSuggestionSelected(String value) {
final String exists = tagsList.firstWhere((text) => text==value,orElse: (){return null;});
if(exists !=null) {
final String isAlreadyInSelectedList = selectedTags.firstWhere((text)=> text==value,orElse: () {return null;});

if(isAlreadyInSelectedList ==null) {
setState(() {
selectedTags.add(value);
tagsList.remove(value);
});
}
}
}

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!

_onSuggestionRemoved(String value) {
final String exists = selectedTags.firstWhere((text) => text==value,orElse: () {return null;});
if(exists !=null) {
setState(() {
selectedTags.remove(value);
tagsList.add(value);
});
}
}

_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

_addSuggestion(String value) {
final String exists = tagsList.firstWhere((text) => text ==value,orElse: () {return null;});
if(exists !=null) {
final String isAlreadyInSelectedList = selectedTags.firstWhere((text) => text ==value,orElse: () {return null;});
if(isAlreadyInSelectedList ==null) {
setState(() {
selectedTags.add(value);
tagsList.remove(value);
});
}
}
else {
final String isAlreadyInSelectedList = selectedTags.firstWhere((text) => text==value,orElse: () {return null;});
if(isAlreadyInSelectedList ==null) {
setState(() {
selectedTags.add(value);
});
}
}
}

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 tag
the 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.

Here is the full code for working tags :

import 'package:flutter/material.dart';
import 'package:flutter_tags/flutter_tags.dart';
import 'package:flutter_typeahead/flutter_typeahead.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: FlutterTagExample(),
);
}
}

class FlutterTagExample extends StatefulWidget {
// List<String> listOfTags = [];

@override
_FlutterTagExampleState createState() => _FlutterTagExampleState();
}

class _FlutterTagExampleState extends State<FlutterTagExample> {
List<String> tagsList = ['apple', 'banana', 'orange', 'kiwi', ''];
List<String> selectedTags = [];

@override
Widget build(BuildContext context) {
return Scaffold(
body: Container(
padding: EdgeInsets.symmetric(horizontal: 20.0),
child: Column(
children: <Widget>[
SizedBox(
height: 200,
),
TypeAheadField(
textFieldConfiguration: TextFieldConfiguration(
onSubmitted: (val) {
print('runtimetype of val is ${val.runtimeType}');
_addSuggestion(val);

}
),
hideOnLoading: true,
hideOnEmpty: true,
getImmediateSuggestions: false,
onSuggestionSelected: (val) {
_onSuggestionSelected(val);
},
itemBuilder: (context, suggestion) {
return ListTile(
title: Text(
suggestion,
),
);
},
suggestionsCallback: (val) {
return _sugestionList(
tags: tagsList,
suggestion: val,
);
// return ;
},
),
SizedBox(
height: 20,
),
_generateTags()
],
),
),
);
}

_onSuggestionRemoved(String value) {
final String exists =
selectedTags.firstWhere((text) => text == value, orElse: () {
return null;
});
if (exists != null) {
setState(() {
selectedTags.remove(value);
tagsList.add(value);
});
}
}
_addSuggestion(String value) {
final String exists = tagsList.firstWhere((text) => text ==value,orElse: () {return null;});
if(exists !=null) {
final String isAlreadyInSelectedList = selectedTags.firstWhere((text) => text ==value,orElse: () {return null;});
if(isAlreadyInSelectedList ==null) {
setState(() {
selectedTags.add(value);
tagsList.remove(value);
});
}
}
else {
final String isAlreadyInSelectedList = selectedTags.firstWhere((text) => text==value,orElse: () {return null;});
if(isAlreadyInSelectedList ==null) {
setState(() {
selectedTags.add(value);
// tagsList.add(value);
});
}
}
}

_onSuggestionSelected(String value) {
final String exists =
tagsList.firstWhere((text) => text == value, orElse: () {
return null;
});
if (exists != null) {
final String isAlreadyInSelectedList =
selectedTags.firstWhere((text) => text == value, orElse: () {
return null;
});

if (isAlreadyInSelectedList == null) {
setState(() {
selectedTags.add(value);
tagsList.remove(value);
});
}
}
}

_sugestionList({@required List<String> tags, @required String suggestion}) {
List<String> modifiedList = [];
modifiedList.addAll(tags);
modifiedList.retainWhere(
(text) => text.toLowerCase().contains(suggestion.toLowerCase()));
if (suggestion.length >= 2) {
return modifiedList;
} else {
return null;
}
}

_generateTags() {
return selectedTags.isEmpty
? Container()
: Container(
alignment: Alignment.topLeft,
child: Tags(
alignment: WrapAlignment.center,
itemCount: selectedTags.length,
itemBuilder: (index) {
return ItemTags(
index: index,
title: selectedTags[index],
color: Colors.blue,
activeColor: Colors.red,
onPressed: (Item item) {
print('pressed');
},
highlightColor: Colors.transparent,
splashColor: Colors.transparent,
elevation: 0.0,
borderRadius: BorderRadius.all(Radius.circular(7.0)),
// textColor: ,
textColor: Colors.white,
textActiveColor: Colors.white,
removeButton: ItemTagsRemoveButton(
color: Colors.black,
backgroundColor: Colors.transparent,
size: 14,
onRemoved: () {
_onSuggestionRemoved(selectedTags[index]);
return true;
}),
textOverflow: TextOverflow.ellipsis,
);
},
),
);
}
}

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.

Have a good day!


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 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.

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.

Performance Monitoring of Flutter App

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!👏


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!.

Advanced Provider in Flutter

Introduction :

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 UI again. We use providers for an easy approach to using state management. The advantage of providers over thesetstate method is that it builds the whole UI again…

Before starting our blog, let us know what topic will be going to cover-up


Table of contents:

FutureProvider in Flutter

ProxyProvider in Flutter

Setup:

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.


For more info visit down the link:

FutureProvider class
API docs for the FutureProvider class from the provider library, for the Dart programming language.pub.dev

ProxyProviderBuilder typedef
API docs for the ProxyProviderBuilder property from the provider library, for the Dart programming language.pub.de
v


Thanks for reading this article ❤

Clap 👏 If this article helps you.

Feel free to post any queries or corrections you think are required…✔

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 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.

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!.

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.


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 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.


Stack And Positioned Widget In Flutter

0

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 the stack and positioned widget, describes its properties, and how to use them in your flutter applications. So let’s get started.


Table of Contents :

Stack Widget

Positioned Widget

Code Implementation

Code File

Conclusion


Stack Widget:

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.

  1. alignment: The alignment determines that.How to align children’s widgets in the stack. It can be top,bottom,center,etc.
  2. 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).
  3. Fit: The fit Property is of type BoxFit.Its use describes how a box is marked in another box. It completes semantics sizing.

These are the some parameters of a Stack widget.

Stack(
alignment: Alignment.center,
textDirection: TextDirection.rtl,
fit: StackFit.loose,
overflow: Overflow.visible,
clipBehavior: Clip.hardEdge,
children: <Widget>[]
),

Positioned Widget:

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:

Positioned(
height: 0,
width: 0,
left: 0,
right: 0,
top: 0,
bottom: 0,
child:(),
)

Demo Module:

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.

Check the code below to better understand it.

Stack(
children: <Widget>[
Container(
width: 150,
height: 150,
color: Colors.green[300],
child: Text(
'Green',
style: TextStyle(
color: Colors.white,
fontSize: 20
),
),
),
],
),

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.

Check the code below to better understand it.

Stack(
children: <Widget>[
Positioned(
top: 30,
left: 30,
height:250,
width: 250,
child: Container(
width: 150,
height: 150,
color: Colors.green[300],
child: Text(
'Green',
style: TextStyle(
color: Colors.white,
fontSize: 20
),
),
),
),
],
),

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Code File:

import 'package:flutter/material.dart';
class StackAndPositionedDemo extends StatefulWidget {
@override
_StackAndPositionedDemoState createState() => _StackAndPositionedDemoState();
}

class _StackAndPositionedDemoState extends State<StackAndPositionedDemo> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Stack & Positioned Widget'),
centerTitle:true,
),
body:Container(
padding:EdgeInsets.all(10),
child:Stack(
children: <Widget>[
Positioned(
top: 30,
left: 30,
height:250,
width: 250,
child: Container(
width: 150,
height: 150,
color: Colors.green[300],
child: Text(
'Green',
style: TextStyle(
color: Colors.white,
fontSize: 20
),
),
),
),
Positioned(
top: 70,
left:60,
width: 250,
height: 250,
child: Container(
width:150,
height:150,
color: Colors.red[400],
child: Text(
'Red',
style: TextStyle(color: Colors.white,
fontSize: 20),
),
),
),
Positioned(
top: 130,
left: 90,
width: 250,
height: 250,
child: Container(
width: 80,
height: 80,
color: Colors.purple[300],
child: Text(
'Purple',
style: TextStyle(color: Colors.white,
fontSize: 20),
),
),
),
],
),
),
);
}
}

Conclusion:

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 widget in 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.


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 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.

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.

Explore Layout Inspector In Flutter

0

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.

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::

Introduction

Debugging Layout Issues

Steps To Inspect Layout In Flutter

Conclusion



Introduction:

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.

Clap 👏 If this article helps you.


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 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 FacebookGitHubTwitter, 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.


By Shaiq khan on May 11, 2023.

Canonical link

Exported from Medium on December 4, 2023.

URL launcher in Flutter

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

url_launcher | Flutter Package
Flutter plugin for launching a URL on Android and iOS. Supports web, phone, SMS, and email schemes.pub.dev


Table of Contents :

Introduction

Setup

Code Implementation

Code File

Conclusion


Introduction :

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.

Code File

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

class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
final String lat = "25.3622";
final String lng = "86.0835";

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Url Launcher Demo'),
),
body: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Card(
color: Colors.blue,
shape: RoundedRectangleBorder(
side: new BorderSide(color: Colors.blue, width: 2.0),
borderRadius: BorderRadius.circular(15.0),
),
child: Padding(
padding: const EdgeInsets.all(13.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.open_in_browser, color: Colors.white,),
SizedBox(width: 5,),
InkWell(
onTap: _launchURL,
child: Text('Open Web url',style: TextStyle(
color: Colors.white
),),
),
],
),
),
),

Card(
color: Colors.blue,
shape: RoundedRectangleBorder(
side: new BorderSide(color: Colors.blue, width: 2.0),
borderRadius: BorderRadius.circular(15.0),
),
child: Padding(
padding: const EdgeInsets.all(13.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.email_outlined, color: Colors.white,),

SizedBox(width: 5,),
InkWell(
onTap: _launchEmail,
child: Text('Open email',style: TextStyle(
color: Colors.white
),),
),
],
),
),
),

Card(
color: Colors.blue,
shape: RoundedRectangleBorder(
side: new BorderSide(color: Colors.blue, width: 2.0),
borderRadius: BorderRadius.circular(15.0),
),
child: Padding(
padding: const EdgeInsets.all(13.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Icon(Icons.navigation_outlined, color: Colors.white,),

SizedBox(width: 5,),
InkWell(
onTap: _launchMap,
child: Text('Open map',style: TextStyle(
color: Colors.white
),),
),
],
),
),
),
],
));
}

_launchMap() async {
final String googleMapsUrl = "comgooglemaps://?center=$lat,$lng";
final String appleMapsUrl = "https://maps.apple.com/?q=$lat,$lng";

if (await canLaunch(googleMapsUrl)) {
await launch(googleMapsUrl);
}
if (await canLaunch(appleMapsUrl)) {
await launch(appleMapsUrl, forceSafariVC: false);
} else {
throw "Couldn't launch URL";
}
}

_launchEmail() async {
launch(
"mailto:rakhi@aeologic.com?subject=TestEmail&body=How are you%20plugin");
}

_launchURL() async {
const url = 'https://flutterdevs.com/';
if (await canLaunch(url)) {
await launch(url);
} else {
throw 'Could not launch $url';
}
}
}

Conclusion

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.

Clap 👏 If this article helps you.


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 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.

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.