Google search engine
Home Blog Page 41

Google Maps in Flutter

Google Maps, we all are quite aware of the fact of how crucial Maps are in our life, from locating a place to locating nearby shops, in our daily commute, taxi, food deliveries. The first thing to observe is how important maps are? and the second thing to observe is that most of the apps these days have maps in them, so Maps in App development are becoming a serious thing from day to day. Now when we are talking about development in Flutter, its a fact that maybe you come across a situation where you want to implement maps in Flutter and the first question after that thought comes is HOW TO IMPLEMENT IT? or WHERE TO START FROM?

In this article, we’ll answer your questions like, maps in Flutter, how to use maps in Flutter, implement google maps in Flutter and will help you from setting it up to creating a small module using Maps in Flutter.
 In this article, we’ll be using the Google Maps plugin for Flutter which has been developed by Flutter team themselves.

Where to start from?

Now, that you’re here, you’ll be curious about a particular question, from where you should I start? It’s probably the first thing that comes to our mind whenever we start with anything, isn’t? Don’t worry, we’ll guide you from prerequisite required to displaying the map on your screen and then moving on to what other things can you do using this plugin. So, Let’s start with setting up your project which will stand as the base on which your map will be displayed.

The setting up process includes two things, namely:

Adding the plugin

1. As you know, we’ll be using the Google Maps Plugin which you can find here. This is the official Google Maps plugin developed by the Flutter team.
 2. Add the plugin as the dependency in the pubspec.yaml file, as shown below.
 3. Now, get the packages using the flutter packages get command.

https://gist.github.com/Aditsyal/ffc8fca87002172fdbdaaed2648fa4e1#file-pubspec-yaml

Integrating Google Maps API key

The next step is the last step before you could start coding for the map in Flutter and undoubtedly the important one as this step involves integrating your Google Map API key into your project for both the platforms Android and as well as iOS.

For Android
Create the Google Maps API key from here
– Add the API key in the AndroidManifest.xml file(android/app/src/main/AndroidManifest.xml).

https://gist.github.com/Aditsyal/ad5491a60fc84918af0492b5a933d657#file-androidmanifest-xml

For iOS
Create the Google Maps API key from here
– Add the API key in the AppDelegate.m file(iOS/runner/AppDelegate.m).

https://gist.github.com/Aditsyal/e4e9054b84f691ebafd12f67dea1fea9#file-appdelegate-m

– Now, add a setting to app’s Info.plist file(iOS/runner/Info.plist).

https://gist.github.com/Aditsyal/eee7d791e44b7ac73b0facc9e7b608a3#file-info-plist

If you’ve done everything as said up till now then you’re all set up but there might be some issues regarding the API key setup which we’ll be answering towards the end of the article. Now, you can start using the GoogleMap widget in Flutter.

Using GoogleMap Widget

So, now that you’ve setup your project and we guess all went good, you can display the map using the GoogleMap widget in Flutter.

https://gist.github.com/Aditsyal/e5115389fd70f6d5628c25a25f88a1d0#file-googlemapwidget-dart

This snippet of code will help you display the map on your app, just with few lines of code and you get the basic map displayed on the screen, you can scroll it, zoom in, zoom out are the basic gestures by default. Look at the snapshot below to understand.

Points to understand from the above snippet:

initialCameraPosition: This gives the starting position of the map when it is opened for the first time. Here, we gave the Latitude and Longitude of Egypt, using the CameraPosition Widget which takes the LatLng in its target property. The Camera here describes the view of the user i.e what position in the map should the user be able to view.

GoogleMapController: It’s the controller for a single GoogleMap instance running on the host platform. This controller is like any other controller be it TextEditingController, this manages various functionalities like camera position, zoom, animation, etc.

onMapCreated: This method is called when the map is created and takes the GoogleMapController as its parameter.

GoogleMap constructor:

Now, that you’re able to display the basic map with least of its functionality we’ll move forward to see what all the functionality does this widget holds as clearly just knowing this won’t be sufficient enough. So, let’s start with getting to know the properties that the GoogleMap widget gives us, here is the constructor of the GoogleMap widget:

https://gist.github.com/Aditsyal/fa2e2d291c74114efc344e5121916afc#file-googlemapconstructor-dart

This constructor tells us the various parameters that the widget takes, so here we can see the list of functionality that this widget provides using the plugin. We already gave you a brief about the onMapCreated and the initialCameraPosition properties, so we’ll be skipping these and will give you a brief about the remaining others,

1. gestureRecognizers: This property tells us which gestures should be consumed by the map. It is possible for other gesture recognizers to be competing with the map on pointer events, e.g if the map is inside a ListView, the ListView will want to handle vertical drags. The map will claim gestures that are recognized by any of the recognizers on this list. When this set is empty or null, the map will only handle pointer events for gestures that were not claimed by any other gesture recognizer.

2. compassEnabled: This property tells us if the map should show a compass when rotated. By default, the value is set to true.

3. cameraTargetBounds: This property tells us the bounds for the map camera target. It is used with GoogleMapOptions to wrap a LatLngBounds value. This allows distinguishing between specifying an unbounded target from not specifying anything.

4. mapType: This property tells us about the type of Map tiles to display. There are five types of tiles
 — none: Do not display map tiles.
 — normal: Normal tiles with traffic, labels and subtle terrain information.
 — satellite: Satellite imaging tiles (aerial photos).
 — terrain: Terrain tiles (indicates type and height of terrain).
 — hybrid: Hybrid tiles (satellite images with some labels/overlays)

5. minMaxZoomPreference: This property tells us Preferred bounds for map camera zoom level. It’s used with GoogleMapOptions to wrap min and max zoom.

6. rotateGesturesEnabled, scrollGesturesEnabled, zoomGesturesEnabled, tiltGesturesEnabled: These fours properties are responsible for the respective gestures on the map like, rotate, scroll, zoom and tilt.

7. myLocationEnabled: This property tells us whether “My Location” layer should be shown on the map. This layer includes a location indicator at the current device location, as well as a My Location button.

Exploring the GoogleMap Widget:

We got the basic map displayed and we got to know what functionality it can have, let us explore some of the functionality practically here:

Device Location:

Let’s start by displaying the user’s location on the map. In the properties above, we came across a property called myLocationEnabled, this property is responsible to display the user’s location on the map.

  1. Set the value of myLocationEnabled to true.

2. Add location permission to both native platforms of your app.

On Android, add either
 <uses-permission android:name=”android.permission.ACCESS_FINE_LOCATION” /> or
 <uses-permission android:name=”android.permission.ACCESS_COARSE_LOCATION” /> to your AndroidManifest.xml file. ACCESS_COARSE_LOCATION returns a location with an accuracy approximately equivalent to a city block, while ACCESS_FINE_LOCATION returns as precise a location as possible, although it consumes more battery power.

On iOS, add a “NSLocationWhenInUseUsageDescription” key to your Info.plist file. This will automatically prompt the user for permissions when the map tries to turn on the My Location layer.

So, by writing a few lines of code to set permissions on the native platforms and by setting myLocationEnabled property to true we get the user’s current location.

Changing MapType:

You can change the type of Map by using the mapType property of GoogleMap Widget and can set to any type, satellite, terrain, hybrid or normal.

We also created a tap to switch the mapType using a floatingActionButton, as we know GoogleMap is just like any another widget in Flutter so that means we can use the Map inside other widgets, so we placed the GoogleMap widget inside the Stack and added a floatingActionButton and gave it the functionality to switch the map between the normal and satellite, follow the code snippet to know more,

https://gist.github.com/Aditsyal/6e50ae85d1d1a99749a128ca10096c53#file-maptype-dart

Enable and Disable Gestures:

GoogleMap widget has gestures property in it, namely rotateGesturesEnabled, scrollGesturesEnabled, zoomGesturesEnabled, tiltGesturesEnabled:

https://gist.github.com/Aditsyal/cd5e487cff3e2d7f53463b852f66ef0a#file-googlegestures-dart

Moving the Camera around:

Now, let’s try to move the camera to a specified Latitude and Longitude, for that we use the animateCamera method which animates the change of map position. It takes the CameraUpdate as it’s parameter which has various features in itself, like

newLatLng(LatLng latLng): It moves the camera to a specified geographical location.
newLatLngBounds(LatLngBounds bounds, double padding): It returns a camera update that transforms the camera so that the specified geographical bounding box is centered in the map view at the greatest possible zoom level.
newLatLngZoom(LatLng latLng, double zoom): It moves the camera to a specified geographical location with a zoom level.
scrollBy(double dx, double dy): It returns a camera update that moves the camera target the specified screen distance.
zoomBy(double amount, [Offset focus]): It returns a camera update that modifies the camera zoom level by the specified amount.
zoomIn(), zoomOut(): It moves the camera closer or further away from the surface of the earth.
zoomTo(double zoom): It returns a camera update that sets the camera zoom level.

These are the certain ways of moving the camera around with respective functionality of their own. Feel free to use them as required by you. Here we gonna use newLatLngZoom(LatLng latLng, double zoom) to move the camera to a specified location using a certain level of zoom.

We created a method _goToNewYork in which we used the animateCamera method to animate the camera move on the basis of latitude and longitude of NewYork with a zoom of 10. Then we created a drawer using the drawer property of Scaffold to display it. Let us show you the code snippet,

https://gist.github.com/Aditsyal/59205c109ded25f043478d83ab839c0f#file-movethecamera-dart

So, we can see the animated movement of the camera from one location to another using the latitude and longitude. We created a bunch of other location and put them in the drawer for you to try move to different location. The GitHub link of the module will be provided in the end.

Set the Marker on the map:

Now that we’re able to move the camera around on the basis of specific latitude and longitude, we’ll try to put the marker on the location we move our camera. Let’s suppose you want to move to New York, so when the camera moves to new york you can see a marker set on the particular location.
 To achieve this we’ll use the markers property of GoogleMap widget which takes a set of marker.

https://gist.github.com/Aditsyal/0f0297594e3ff63912113a6b2dbfac5f#file-setthemarker-dart

Now we want the marker to be set as the user moves to the specified location, so we created a marker inside the _goToNewYork method inside the setState() method.

https://gist.github.com/Aditsyal/7d0f293521d085e8e9a6cb32fc79dd21#file-markers-dart

Marker marks a geographical location on the map. Here, the markerId is the unique id of each marker and position property takes the LatLng of the location. This gives us

Now, let’s add some information on the marker so that when it’s tapped the information is displayed. For this we’ll use the infoWindow property of the Marker widget which gives us a title, snippet, to give the title to the marker and desc to the marker.

https://gist.github.com/Aditsyal/d6709ecb54efa5bd2e227a270c7c5120#file-infowindow-dart

Now that we added the marker on the map at our desired location using the latitude and longitude of the place and also gave the marker some text to be displayed when tapped. We just showed the implementation of how to do it, know it totally depends on you how to use it and how to implement it. You can find the complete module on github.

Conclusion:

GoogleMap widget is just like any other widget in Flutter that means this widget can be placed inside any other widget, like Listview, Stack, Column, Row, Container and so on, you can even transform it, clip it but we know why would someone clip it we’re just telling you that you can perform anything on the map as its a widget. So be creative, explore more and even let us know of something you come across.

Do let us know how was the article and wish we could cover everything in the article, every feature but that would just mean writing a book and that’s not what you want and what we want. We tried to explain from the root from how to install it, to some basic feature which you might require in regular use if you’re using map.

Aditsyal/flutter_maps
Google Maps in Flutter. Contribute to Aditsyal/flutter_maps development by creating an account on GitHub.github.com


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 FacebookGitHubTwitter, and LinkedIn for any flutter-related queries.

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

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


Complete Guide to Flutter State Management with Provider 2026

What is Provider?

A dependency injection system built with widgets for widgets. provider is mostly syntax sugar for InheritedWidget, to make common use-cases straightforward.

Let’s build a very simple navigation app with the Provider package.

We will build a navigation drawer app and when we tap on the item on the drawer the screen replaces with another screen just like Navigation menu fragment transaction.

This is just like a Fragment Transaction in an Android app.

Step 1: Add the dependency in your pubspec.yaml.

provider : <latest-version>

Step 2: Create a Provider class

/media/72482944219ad3fe84e7b3bb2943a8ab

In this provider class, we have implemented our logic which is to update the current navigation value.

updateNavigation will update the current value of the navigation and notify the listener.

To notify, you need to add the ChangeNotifierProvider to the root of the Widget tree.

home: ChangeNotifierProvider<NavigationProvider>(
builder: (_) => NavigationProvider(),
child: HomePage(),
),

Step 2.1: Update the UI

Unlike Bloc, you do not need to use the StreamBuilder to update the UI.

navigation.getNavigation will return the body as declare in the provider class above.

Step 2.2: Update the UI with Consumer

You can also use Consumer to get the value and update the UI then you do not need to use

Provider.of<provider-class>(context);
body: Consumer<NavigationProvider>(
builder: (context, navigationProvider, _) =>
navigationProvider.getNavigation),

Step 3: Add the drawer

/media/834f4d14010bf649ffd6cc2c12994846

Whenever we tap on any drawer item, first it will close the drawer menu using Navigator.of(context).pop()then it updates the provider which changes the navigation value and the provider will update the UI.

/media/e7895e2bdaf6f0cb99ca251d6a54adc4

Now its time to run the app.


We have also linked a repo.

ashishaeologic/Flutter-ProviderExample
Contribute to ashishaeologic/Flutter-ProviderExample development by creating an account on GitHub.github.com

Thanks for reading this article ❤

We got something wrong? Let me know in the comments. We 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 FacebookGitHubTwitter, and LinkedIn for any flutter-related queries.

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

Related: State Management In Flutter-Provider

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


How to manage state with BLoC in Flutter 2026

It’s very hectic to manage state in flutter it when we have a complex UI and complex widget tree.
Before we jump into the state handling using bloc you need to understand about state management.

Why we need State management

Whenever we perform an operation on the widgets, suppose we have a RaiseButton and whenever we tap on it, it updates the Text, the very simple method is to use the setState(). It is not a problem if you have a small widget tree but you need to avoid the setState() if we have a complex Widget tree.

Why not setState()?

Suppose we have this Widget tree and we need to update only on development in the Widget tree but if we use setState(), it will rerender the whole widget tree and update all the elements.

There are few techniques for managing the state :

InheritedWidget: It allows you to pass the state to its child widgets, to youse the InheritedWidgets you need to add the Inherited widgets at the root of the widget tree but the problem with the InheritedWidget is that state is final when you are using theInhertedWidget so you cannot mutate the state.

Scoped Model: ScoperModel provides a better way to access, mutate and update widget state and it is built on top of InheritedWidget.
If your Model gets complex, it might be challenging to know when to properly call notifyListeners() to avoid unnecessary updates.

let’s talk about Bloc

Bloc

BLoC stands for Business Logic Component. Before we dive into bloc we need you to understand the Sink and Stream.

We add the data into the Sink and listen to the streams of data through Stream and updated the UI using StreamBuilder.

Let’s code

We will build a navigation drawer app and when we tap on the item on the drawer the screen replaces with another screen.

This is just like a Fragment Transaction in an Android app.

Step 1: Create a Bloc

We have created a class which contains a StreamController, StreamControllercontrols the stream of data and we have a Streamwhich will be used in the StreamBuilderto get the data flowing in the Stream.

Step 2: Create a Provider class

In this provider class, we have implemented our logic which is to update the current navigation value.

Step 3: Implement Provider class into Bloc

https://gist.github.com/ashishrawat2911/b83d0a0c78ea75e6a57d7b5c52771d01#file-bloc-dart

Now we have a bloc class which will update the navigation value and sink the value in the stream and uses it in StreamBuilder.

Step 4: Update the UI using StreamBuilder

Now NavigationDrawerBloc bloc = NavigationDrawerBloc();

So we have wrapped the body with StreamBuilder so whenever there is any change in the stream it will automatically update the body.

Add the drawer

https://gist.github.com/ashishrawat2911/edb453caeb8c888372f3f4560488eb29#file-drawer-dart

Whenever we tap on any drawer item, first it will close the drawer menu using Navigator.of(context).pop()then it updates the bloc which changes the navigation value and the data flows through the stream and StreamBuilderupdates the UI.

Make sure you close the stream, we can do is call the dispose method which we create in the bloc class bloc.dispose() .

https://gist.github.com/ashishrawat2911/1ee5434589f60cbc38ad889bfa584adc#file-navigationui-dart

Now its time to run the app.


we have also linked a repo.

ashishrawat2911/flutter_navigation_drawer_bloc
Contribute to ashishrawat2911/flutter_navigation_drawer_bloc development by creating an account on GitHub.github.com

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.

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 FacebookGitHubTwitter, and LinkedIn for any flutter-related queries.

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

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


Complete Guide to SharedPreferences in Flutter for 2026

What is SharedPreferences?

SharedPreferences is used for storing data key-value pair in the Android and iOS.

SharedPreferences in flutter uses NSUserDefaultson iOS and SharedPreferences on Android, providing a persistent store for simple data.

Why use SharedPreferences in Flutter?

Suppose you wanna save a small value (a flag probably) that you wanna refer later sometime when a user launches the application. Then shared preference comes into action.

We do not use SQLite for saving small values because then you will need to write lengthy codes and supporting classes.

Shared Preference let you read and write key-value pair in a couple of lines easily. But always remember, shared preference is not a solution for you to keep complex relational data.

How to use SharedPreferences in Flutter?

Before using SharedPreferences, you should know that Flutter SDK does not have support SharedPreferences but fortunately, the shared_preferences plugin can be used to persist key-value data on disk.

Implementation

Step 1: Add the dependencies

Add dependencies to pubspec.yaml file.

dependencies:
flutter:
sdk: flutter
shared_preferences: "<newest version>"

Step 2: Import shared_preferences.dart

import 'package:shared_preferences/shared_preferences.dart';

Step 3: Save data

We can only add int, String, double and bool using SharedPreferences.

There are setter methods in the SharedPreferences class which take two parameters, key and value.

keys are only string values

Saving String value

https://gist.github.com/ashishrawat2911/0cdad3ca524d06a455d0986687567848#file-addstringsf-dart

Saving int value

https://gist.github.com/ashishrawat2911/d57dbfd9fc465cfe1c20f65be725cef2#file-addintsf-dart

Saving double value

https://gist.github.com/ashishrawat2911/bac6897604ac01b544915a3ef25c4aff#file-adddoublesf-dart

Saving boolean value

https://gist.github.com/ashishrawat2911/362c16deae76b40b8d2b357ebc68269c#file-addboolsf-dart

Step 4: Read data

When we are reading the data from the storage through SharedPreferences we only required to pass the key only.

https://gist.github.com/ashishrawat2911/2bc3d85c0a31bd1c2bf9009a8f865f88#file-readvaluessf-dart

If the value is not present in the storage then we might get a null value.
To handle this we can use

int intValue= await prefs.getInt('intValue') ?? 0;

Step 5: Remove data

To remove the data from the storage we provide the key in the remove(String key) method.

https://gist.github.com/ashishrawat2911/e9ba0b8bc3fcf1aae1fe7c2ca78cfc2d#file-removevaluessf-dart

Check value if present or not?

SharedPreferences prefs = await SharedPreferences.getInstance();

bool CheckValue = prefs.
containsKey('value');

containsKey will return true if persistent storage contains the given key and false if not.


Thanks for reading this article ❤

Connect with me on Linkedin and Github

From Our Parent Company Aeologic

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

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

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 FacebookGitHubTwitter, and LinkedIn for any flutter-related queries.

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

Related: SMS Using Twilio In Flutter

Related: Working with Callback In Flutter


Frequently Asked Questions

How can I save user data like preferences or login status in a Flutter app?

You can use SharedPreferences, a built-in package in Flutter, to store small amounts of persistent data on the device.

What is the process for setting and retrieving data using SharedPreferences in Flutter?

You can use `setString`, `setInt`, `setBool`, etc., to store data, and `getString`, `getInt`, `getBool` to retrieve it.

How secure is the data stored using SharedPreferences in Flutter?

Data stored with SharedPreferences is not encrypted, so it’s recommended to use it for simple user preferences and not sensitive information.

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

BLoC pattern in Flutter | FlutterDevs

By the title, you must have got an idea about what this article will be. As Flutter is growing day by day and so it’s developers and we as a developer always look for an easy way to deal with the code. So as the title speaks out loud we’ll be covering BLoC pattern in detail answering various questions like,

What is BLoC Pattern?
 Why BLoC?
 When to use BLoC?
 and, How to implement BLoC?

But in this article, we’ll only be covering the first three questions in detail and the very next article will solely feature BLoC implementation with an example.

What is BLoC pattern?

BLoC a.k.a Business Logic Components is a design pattern presented by Paolo Soares and Cong hui, from Google at the DartConf 2018.
Initially, BLoC pattern was conceived to allow the reuse of the very same code independently of the platform: web application, mobile application, back-end. So yeah, this pattern was developed aiming to ease the workload on developers end while developing apps for a different platform with the idea of code reusability. Watch the video below to get more insight on the baby steps set by BLoC.

So, if you watch this video then you will understand how using BLoC you can share most of your code to different platforms.

To know BLoC in detail let’s first get to know about Streams.

Streams

In a general sense, a stream is a continuous flow or succession of anything.
 For example, this is a stream of cats 😛

https://cdn-images-1.medium.com/max/720/1*ccPKTUTwZtt8HADzCtBLwA.gif

But technically speaking, Stream is nothing but a continuous flow of data.
 Let’s take an example of Conveyor Belts. A Conveyor Belt has two ends, from one end an item is passed(input), then it is processed and after processing, it gets out from another end of the belt(output).

Key terms:

  • Stream, the conveyor belt is called as a stream
  • StreamController, this is what controls the stream
  • StreamTransformer, this is what processes the input data
  • StreamBuilder, it’s a method that takes stream as an input and provides us with a builder which rebuilds every time there is a new value of a stream
  • sink, the property which takes an input
  • stream, the property which gives the output out of the Stream

So now we got a bit of an idea about Streams. Back to Flutter, I think the one of the main hindrance one comes across while coding in Flutter is to deal with UI and everything else as in Flutter we don’t have any intermediatory designing language for the UI like in Android we have XML, instead in Flutter we write all the code at one place(traditionally). That’s where BLoC comes in play and helps remove this hindrance in an efficient way.

  • BLoC not only solves the code sharing problem but also leverages Streams functionality in order to manage and propagate state changes in Flutter.
  • BLoC helps us to separate Business Logic from UI. In other words, UI components should only worry about the UI and not the logic.
  • So, even though Flutter lacked an intermediatory language for UI using BLoC one can separate both the things making independent on each other.
  • If you’re an Android developer, then think of BLoC object as a ViewModel and of StreamController as a LiveData.

What does all this mean?

As already discussed BLoC makes use of Streams, we can infer the following things,

https://www.didierboelens.com/images/streams_bloc.png
  • The input is taken using the sink property
  • The output is provided using the stream property
  • Widgets send events to the BLoC via sinks
  • BLoC notifies the widgets via streams
  • Now that business logic and UI components are separated, we may change the Business Logic of the app at any time without any impact on the UI
  • Similarly, we may change the UI without having any impact on the Business Logic

Why use BLoC?

Now that you got an idea about what BLoC is, you might be thinking why to use it for state management when there are already a few other ways to deal with it, let’s discuss them and see why BLoC is efficient out of all.

setState()

The setState() method notifies the framework that the internal state of the object has changed. Whenever you change the internal state of a State object, make the change in a function that you pass to setState:

setState(() { _myState = newValue } );

Calling setState notifies the framework that the internal state of the object has changed in a way that might impact the user interface in this subtree, which causes the framework to schedule a build for this State object.

Problems with this:

  • The whole widget tree gets rebuilt every time state of even a single widget changes.
  • It doesn’t help to separate the UI components and Business logic.

InheritedWidget

It is a special kind of a widget that defines a context at the root of a sub-tree and can efficiently deliver this context to every widget in that sub-tree.

As said, it can

  • Propagate data down the tree
  • Update widgets on rebuild

Problems with this:

  • The state is set to final which means it is immutable.
  • It doesn’t provide any dispose method to free the resources and to avoid data leaks.

Scoped Model

It is an external third party package maintained by Brain Egan. It is built on top of InheritedWidget offering a slightly better way to access, update and mutate the state. It allows you to easily pass a data model from a parent widget down to its descendants and also rebuilds all the children that use the model when the model is updated. To check for any change a method notify listeners() is used by Scoped Model.

Problem with this:

  • As the model gets more complex it’s hard to keep track of when you should call notifylisteners().

So, all the above-mentioned approaches have one or the other demerits which didn’t stand as the best way of state management in FLutter and that’s where BLoC pattern stands to be efficient as it deals with all the demerits of these approaches.

Watch the video for a better perspective,

When to use BLoC?

To get to know when to use BLoC and when not to use, we must be aware of the concept of Local state and Global State.

Local State vs Global State

Taking an example you might have used: Imagine a login form, where the user has to enter the username and password and then there is an API communication to validate the credentials of the user upon which authentication works. So here and form of validation on the login form is considered as Local state since its scope is applied to this component only and the rest of application has nothing to do with it. While the API communication upon which the authentication of the user was depended is considered as Global state since it’s upon this authentication the entire scope of the app is dependent.

So, the basis on this local state and global state scope of the different methodology is dependent, see the table to know more.

Redux is also a state management approach. For dealing with local state BLoC is best recommended, while for Global state BLoC maybe used when the app is simple and not much complex but not recommended. For Global state, Redux is highly recommended.

So, this article gives you the necessary details about BLoC, from what is BLoC, why to use BLoC and when to use BLoC, the last question i.e How to implement bloc will be covered in a totally different article where Login form authentication will be performed using BLoC.

We hope this article was helpful to you and if there is something that we left then do let us know in comments and also if you want something else for us to cover in Flutter.

From Our Parent Company Aeologic

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

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

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, and Twitter for any flutter related queries.

Related: Switch Theme Using Bloc With Cubit In Flutter

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

Concurrency In Flutter

0

Concurrency is pivotal in versatile application advancement since it permits an application to play out numerous errands at the same time without obstructing the fundamental thread. Flutter’s customizing language is Dart, which is single-threaded of course. This implies it executes in a solitary thread. In any case, on the off chance that we work on a huge application with central processor escalated tasks, the principal thread might turn out to be slow, influencing the application’s performance.

In this blog, we will explore the Concurrency In Flutter. We will l take a gander at how to foster enormous applications without sacrificing performance in your 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 concurrency?

Importance of Concurrency In App Development

What is an isolate?

How do they work?

Example 

Conclusion



What is concurrency? :

Concurrency alludes to the most common way of managing many tasks without a moment’s delay. It includes coordinating and executing numerous tasks over time, however not dependably simultaneously. In software development, it implies executing a few calculations or cycles simultaneously, which can essentially work on the performance and responsiveness of users.

Concurrency includes dealing with numerous tasks by exchanging between them, giving the deception that they are running at the same time. This is especially significant in conditions where assets like CPU and memory are restricted, like mobile devices.

Importance of Concurrency In App Development:

The importance of concurrency in app development is:

  • Responsiveness: Mobile applications need to stay receptive to client collaborations. Without concurrency, long-running undertakings like network requests or information handling can obstruct the main thread, causing the application to freeze and giving an unfortunate client experience.
  • Performance: Proficient concurrency takes into consideration better asset use, guaranteeing that undertakings like getting information, handling pictures, or dealing with client input are performed flawlessly without over-burdening the framework.
  • Battery Duration: Appropriate administration of concurrency can prompt better battery use by enhancing how undertakings are planned and executed, lessening pointless CPU utilization.
  • User Experience: Clients expect portable applications to be quick and responsive. Concurrency guarantees that foundation undertakings don’t slow down the smooth activity of the application’s UI, giving a consistent encounter.

What is an isolate?:

Isolates in Dart are an extraordinary method for running different errands simultaneously without dialing back the main thread or freezing the UI. They are especially valuable for running errands that require a great deal of handling power.

Isolates have their own memory store, and that implies they don’t impart memory to the fundamental string or other isolates. This assists with forestalling normal issues that can happen when various strings access shared memory, for example, race conditions or deadlocks.

This isolation guarantees that there are no race conditions or need for synchronization, making simultaneous programming more secure and more clear. Each separate has its own occasion circle and microtask line, permitting it to execute undertakings freely of the primary seclude (the fundamental string).

How do they work?:

Dart utilizes isolates to establish a different execution climate that can run lined up with the principal thread. This considers simultaneous programming by empowering various isolates to run simultaneously, each with its own memory heap, event queue, and event loop. Accordingly, isolates can perform free errands without offering memory or state to other isolates.

  • Isolate Creation: In Dart, you can make a new separate by conjuring the Isolate.spawn() capability. This capability requires two contentions: a high-level capability or a static technique that fills in as the section point for the function, and an underlying message, which is generally a SendPort object. The SendPort object is utilized to lay out a correspondence channel between the recently produced isolate and the spawning isolate.
  • Communication through Message Passing: Isolates don’t share memory space, which guarantees that each disconnect has its own stack and forestalls direct admittance to another segregate’s information. To permit communication between isolates, Dart utilizes a system known as message passing, which includes SendPort and ReceivePort objects. A SendPort communicates messages to another segregate, while a ReceivePort gets messages from another isolate. Messages are passed by value, not by reference, implying that a duplicate of the information is sent, guaranteeing that the first information stays unaltered and secure in its own isolate.
  • Execution of Tasks: Each isolate has its own occasion loop and occasion queue. When a disengage gets a message, it’s additional to its occasion queue. The occasion loop then processes these messages individually by executing the related tasks or capabilities. This cycle goes on until the occasion queue is unfilled or the isolate is ended. This component empowers simultaneous task performance, which helps the proficiency of your Dart and Flutter applications.
  • Termination of Isolates: An isolate can be ended in two ways: automatically utilizing the Isolate.kill() technique, or naturally when it has finished every one of the tasks in its occasion queue. In certain circumstances, a particular message can be shipped off the isolate, training it to end itself.

Example :

In the accompanying code, a new isolate is made to compute the amount of a list of a million numbers. The sumNumbers capability, which is the section point for the isolate, gets the list of numbers and a SendPort for correspondence with the fundamental isolate. It works out the aggregate and sends it back to the fundamental isolate. The primary isolate tunes in for the sum, prints it, and afterward ends the isolate and shuts the ReceivePort.

import 'dart:isolate';

void sumNumbers(List<dynamic> data) {
List<int> numbers = data[0] as List<int>;
SendPort sendPort = data[1] as SendPort;
int sum = 0;
for (int number in numbers) {
sum += number;
}
sendPort.send(sum);
}

void main() async {
ReceivePort receivePort = ReceivePort();
List<int> numbers = List<int>.generate(1000000, (index) => index);
Isolate isolate = await Isolate.spawn(sumNumbers,[numbers, receivePort.sendPort]);
receivePort.listen((message) {
print('Sum: $message');
receivePort.close();
isolate.kill();
});
}

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

Sum: 499999500000

Process finished with exit code 0

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying up the Concurrency In Flutter in your projects. We will show you how isolates can handle heavy computation tasks in a separate thread to keep your app running smoothly. We also provided an example of when it’s appropriate to use isolates in your application. 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.

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.

Related: SMS Using Twilio In Flutter

Related: Using SharedPreferences in Flutter

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


Animations in Flutter — Getting Started #1

0

Introduction

Animations in a mobile app adds interactivity to the UI as well as some visual effects to it. Animations, when used correctly, can make a huge difference in how user perceives your app. Every mobile developer wish to add animations in their app, but, they are unsuccessful in doing so, because, there is a lot of complexity and lot of things, a developer has to learn before adding animations.

That’s where Flutter comes in…

Flutter has a very good Animation library that allows you to create complex animations that can run constantly at 60 frames per second very easily.

Overview

In this blog post, I’ll tell you about basics/foundation animation concepts in Flutter that allows you add complex animations very easily.

1. Animation Class

All the animations in Flutter are provided by Animation class. According to the documentation, Animation contains a generic type variable Animation<T> which means that what type of value should should be animated. Most common type of Animation used is Animation<double>

To create and run the animation, we need Animation and AnimationController objects. We’ve seen the Animation class in the above section. In the next section, Let’s see the AnimationController class

2. AnimationController

It is basically a controller for animation, which lets you to perform various operations with the current animation

  • Play an animation either in forward or in reverse direction.
  • Pause current playing animation
  • Stop current playing animation
  • Define range of animation — min and max value

https://gist.github.com/flutter-devs/e08e375c0684b571ecbfb7bb3dbad622#file-home-dart

  • In line 7, we are providing SingleTickerProviderStateMixin with the _HomeScreenState class which basically means that we are providing Ticker with the help of SingleTickerProviderStateMixin class and linking it with this class.

Ticker is nothing, but a class which sends a signal at almost regular interval (e.g. Like watch ticks at every second). At each tick, the Ticker invokes it’s callback method(s)

  • In line 14, object of AnimationController is initialised, and it expects 2 parameters — vsync and duration

vsync property binds the AnimationController object with the Ticker and duration specifies the time till which given animation will run.

  • In line 15, we’re attaching the listener with AnimationController object and calling setState() which ensures that, each time the value changes, the Widget is rebuilt
  • In line 18, animation is started using forward() function provided by AnimationController
  • At last, make sure to dispose the given AnimationController object in dispose() method.

Now, you understood the basic concepts of Animation, now, Let’s see the different types of animation

Basic Types of Animation

  • Tween
  • Curved

Tween Animation

Tween Animation is the type of animation which interpolates between the given range. It linearly interpolates between the begin and end value. In the case of Animation<double>, it linearly interpolates between only double values, but, in the case of Tween, it can interpolates between colors, borderRadius, etc.

https://gist.github.com/flutter-devs/f69c3fec53107e7dd96f606d09072729#file-home-dart

In the above code, Tween animation is initialised by giving it’s begin and end value. In this case, we’re specifying 0.0 and 1.0 for begin and end respectively that means it’ll linearly interpolates between 0.0 and 1.0 values and at last, call the animate method and specify the type of animation inside it.

If you want to interpolate between BorderRadius, then, either specify BorderRadiusTween or Tween<BorderRadius>

https://gist.github.com/flutter-devs/33df4af5be42b43b15ba9edd01501e0f#file-home-dart

CurvedAnimation

CurvedAnimation is the type of animation which applies curve to the animation. It provides many different types of curves such as easeIn, fastOutSlowIn, easeOut, bounceIn, and many more. Animation applied through CurvedAnimation follows non-linear curve.

To have a better visual look of different types of curves, head over to this
link

https://gist.github.com/flutter-devs/162d4585c70e71b7db7d78ac0800654f#file-home-dart

First, initialise the AnimationController and after specifying the range of animation with the help of Tween, then specify the CurvedAnimation. CurvedAnimation expects two parameters which are required and one optional parameter —

  • curve: It denotes the curve that is to be followed by animation while the particular widget is animating
  • parent: It links the AnimationController with the Animation
  • reverseCurve: It denotes the curve that is to be used in reverse direction

We got something wrong? Mention it in the comments. We would love to improve.

If you learnt even a thing or two, clap your hands 👏 as many times as you can to show your support!

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 FacebookGitHubTwitter, and LinkedIn for any flutter-related queries.

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

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


How to develop Flutter web apps in 2026

0

Flutter was introduced back in May 2017 with the general idea of Cross-Platform app development initially for Android and iOS and aiming for Web and Desktop platform. It’s been quite a while when Flutter for Android and iOS went into stable version and even more since the first mention about using Flutter for the web. Earlier the project was codenamed HummingBird but at the Google IO earlier this month, Flutter for Web was made public as Technical Preview aiming to build highly interactive and graphics-rich content for the web. While releasing Flutter 1.0 on Dec’18 the Flutter team disclosed their further plan and goals in Flutter which involves making Flutter build apps for web and can be read from their Roadmap.

Flutter for web is a code-compatible implementation of Flutter that is administered using the various standard web technologies like HTML, CSS, and Javascript. One interesting thing that amuses me is the fact that one can reuse the existing Flutter code to be deployed into any web server, all the features of Flutter and you don’t even have to use any browser plugin.

Things to cover in this article:

  1. Overview of Flutter for web
  2. Creating your First web project
  3. Limitations

Overview of Flutter for Web

So, Yes! Flutter being officially released for the web takes development using Flutter beyond mobile platforms, initially what was restricted just to mobile platforms has now spread its wing across the web and desktop (Linux, Window and MacOS, which we’ll talk about in another article).
Let’s understand the structure and see how Flutter works beneath the hood and compare it with the structure of Flutter for web.

Flutter architecture

So, this is the Flutter architecture for iOS and Android,

  1. The first layer in the structure is Flutter framework layer which is responsible for all the built-in widgets and gestures.
  2. The next second layer is the Flutter engine which is written in C++ and uses Google’s Skia as a graphics library.
  3. Then there is a thin runner layer which is responsible for running the app on individual platforms.
  4. And the last layer is the hardware layer which provides the necessary hardware where the app runs.
Flutter for web Architecture

Now, let us see the architecture of Flutter for Web,

  1. The first layer is similar to the general Flutter architecture consisting Flutter framework layer which is responsible for all the built-in widgets and gestures.
  2. The Flutter engine has been replaced with Flutter web engine which is a lower level implementation of Flutter widgets and rewritten them. It generates dart code which is converted into HTML and CSS.
  3. Dart2js compiler is used to compile the code into javascript which is ready to run on your browser.

Look at the diagram below to have a more detailed and vivid view of the internal working of the web architecture.

Creating your first web project

Now, that we understand the gist about how the Flutter web works or what’s actually happening underneath the hood, let’s move forward and set up our IDE for the web project.

Installation:

Here is the step by step approach of how to create your basic web project:

  1. First, you need to make sure you Flutter version is 1.5.4 or higher and Dart 2.3 must be installed.

flutter channel master && flutter upgrade

2. To make sure that your Flutter is updated, run the following command

flutter doctor

3. Next, you need to add the .pub-cache/bin to your PATH as you will be installing a global package:

For Windows:
C:\Users\<your-username>\AppData\Roaming\Pub\Cache\bin

Restart your system.

For Linux:
$HOME/.pub-cache/bin

For MacOS:
$HOME/flutter/.pub-cache/bin

First Web Project:

  1. In VSCode use ctrl+shift+p to open the command palette and type,

Flutter:New Web Project

2. VSCode will ask permission to install the stagehand, stagehand is a Dart project generator. Accept it and the VSCode will automatically install the stagehand and if you want to install it manually then type the following command in your terminal,

pub global activate stagehand

3. Then, give the name and project location to your project and stagehand will generate a basic project ready for you.

4. It will automatically run pub getcommand to load the necessary packages for your project.

5. To run the basic project you’ll need to install the webdev, normally the VSCode will ask for the permission to install webdev automatically but if you want to install it manually then type the following command in your terminal,

pub global activate webdev

6. To run the project type the following command in the terminal

webdev serve

Basic web project

Understanding the Project Structure:

Let’s see the basic project structure of Flutter for Web project,

Project Structure

The structure has the following components:

  1. dart_tool directory
  2. lib directory
  3. web directory
  4. other basic necessary files required by the flutter

lib directory:

lib directory

The lib directory is what contains all your code just like your normal Flutter project, it has a main.dart file which is just like any main function in Flutter. All the code required for the Flutter app goes inside this directory.

web directory:

web directory

The web directory has two files namely,
1. index.html:

index.html

This is the starting point of your application which loads the application.

2. main.dart:

web/main.dart

The main file in the web directory is the starting point of Flutter web application. This file calls the main method of the lib directory which contains all your code after initializing the engine.

Using assets in Flutter web application:

When you create a web project, the project structure doesn’t include any assets folder and if you try to run any pre-existing application you might come across a situation where your icons won’t be visible. 
The assets folder has to be inside the web directory of the Project.

assets

For your application to display all the icons you must include FontManifest.json file contains all the fonts and icons required by your app.

import ‘package:flutter_web/material.dart’;

Limitations:

Even though Flutter announced the Flutter for web, it is still in Technical preview stage. You can do a lot of things but since it’s still in the early stages there are chances that things can change and as a developer, it will take time for you to explore it without any limitations.

  1. As you may have noticed that you aren’t importing import 'pacakage:flutter/material.dart';instead you’re importing import 'package:flutter_web/material.dart';.This is due to the fact that flutter_web is a forked repository of existing flutter framework. This is the temporary fork and will be merged into one soon.
  2. Plugins are not yet supported completely.
  3. As its just the beginning, the performance might be slow.
  4. Restrictions on the support of all Flutter APIs.
  5. Hot reloading the web page involves a trick. Either you have to manually refresh the web page or use the terminal command to Hot reload webdev serve --auto restart.

So, We hope that you were able to create your first basic Flutter project for web and it runs successfully. You may need to handle the screen responsiveness of your app to deal with different screen sizes. We have a small module related to Flutter for web, you can view it from here.

To watch the I/O video related to Flutter for web,

We hope you liked the article and if there is something you wanna convey then you can reach us at flutterdevs.

You can also read our related articles:

BLoC pattern in Flutter – FlutterDevs
By the title, you must have got an idea about what this article will be. As Flutter is growing day by day and so it’s…flutterdevs.com

From Our Parent Company Aeologic

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

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

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

Frequently Asked Questions

How can I start developing web apps using Flutter?

Begin by installing Flutter on your system and setting up Dart, then create a new project with the ‘flutter create’ command and use web as the target platform.

What are the key differences between developing mobile apps and web apps using Flutter?

The main difference lies in the web-specific widgets used, such as WebView instead of CupertinoApp or MaterialApp for mobile.

How can I handle different browser compatibility issues while developing web apps with Flutter?

Flutter abstracts away many of the cross-browser compatibility issues, but it’s still important to test your app on multiple browsers for optimal results.

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

Draggable and Drag Target in Flutter

0

Flutter provides a variety of Widgets through which we can build any kind of UI. But more than a design, your app should be interactive so that it can be easily accessed to users. In this article, I will be building the following app which makes use of Draggable and DragTarget. So, first of all, let’s look at what are Draggable and DragTarget in Flutter.

Draggable

As the name suggests, Draggable means a widget which can be dragged or moved on the screen. Let’s take an example :

Draggable example

Here’s the code for this:

https://gist.github.com/flutter-devs/51e07c5c417e7246527f8575f006691b#file-main-dart

Draggable class generally made of four main parameters :

  1. child: Widget which can be dragged or to be displayed when draggable is stationary.
  2. feedback: Widget to be displayed when drag is underway.
  3. childWhenDragging: Widget to be displayed in the original place of Draggable when drag is underway.
  4. data: It contains the information dropped by Draggable at DragTarget, it is useful when we are using multiple Draggable and DragTarget.

The draggable class provides some callback functions, such as :

  1. onDragStarted: Called when the Draggable widget starts to drag.
  2. onDragCompleted: Called when Draggable is dropped on DropTarget and DropTarget has accepted the Draggable.
  3. onDragEnd: Called when Draggable is dropped on DropTarget. This contains the velocity and Offset of Draggable when it was dropped.
  4. onDraggableCancelled: Called when Draggable is dropped but not accepted by DragTarget.

DragTarget

As the name suggests, DragTarget means a widget which provides target or destination to Draggable, it also receives the data from a Draggable. Let’s take an example :

Here’s the code for this :

https://gist.github.com/flutter-devs/6b79ccd39b8653c7317c15d030de38cd#file-main-dart

  • In line 4, if the value of isSuccessful is true then Container with FlutterLogo child will be returned, else empty Container will be returned.
  • In line 24, onWillAccept will contain the data of a Draggable, if you want your DragTarget to accept the data of Draggable then return true like in this case. After this control will be transferred to the onAccept property of DragTarget (line 27).
  • In line 27, inside onAccept I am changing the value of isSuccessful to true, as the Draggable is dropped on DragTarget and data is accepted by DragTarget.

DragTarget class generally made of four main parameters:

Builder

Takes a function which is called to build the contents of DragTarget, we can build different widgets based on Draggable. This takes three parameters:

  1. BuildContext: Context of a Widget.
  2. candidateData: It contains the list of draggable data which will be accepted by DragTarget.
  3. rejectedData: It contains the list of Draggable data which will not be accepted by DragTarget.

onWillAccept

Takes a function which provides the data of Draggable to use as a parameter and returns bool based on whether Draggable will be accepted or not, if onWillAccept returns true then onAccept is called.

onAccept

Takes a function which provides the data of Draggable which was accepted by DragTarget.

onLeave

Called when Draggable leaves the DragTarget and not dropped into DragTarget.

I hope your basics of Draggable and DragTarget are clear now. Let’s move to our demo app which I will be building using these two widgets.


Demo App

I’ll create a simple app which contains the stack of cards as a Draggable and user has to drop that card to DragTarget until the stack becomes empty, also there is a Reset button through which app can be reset again.

Video of Demo app built using Draggable and DragTarget

Prerequisite

  1. I’ll be building this app using Provider architecture, so you must know the concept of Provider and how it works.
  2. Basics of Draggable and DragTarget which were covered earlier in this blog.

Enough of theory, let’s get started.

First, I’ll create a basic structure of the App. Our app contains two screens — SplashScreen and HomePage.

Open main.dart file and add the following code.

https://gist.github.com/flutter-devs/f068b50a4671f8308e9cb97d3091e91b#file-main-dart

  • At line 12, HomePage is wrapped by ChangeNotifierProvider, it listens to ChangeNotifier, pass the value to its descendants and rebuilds the descendants whenever notifyListeners() get called.
  • ChangeNotifierProvider takes a builder function basically which is used to initialize our data part of our app which can be changed.

Now, Create five files mentioned below :

  1. data.dart: Contains business logic.
  2. cardItem.dart : a model class for a single item in the list of Draggable.
  3. constants.dart: Contains some static data or constants.
  4. strings.dart: Contains some strings which I’ll be using in this app.
  5. colors.dart: Contains some colors which I’ll be using in this app.

Open colors.dart and add the following code.

https://gist.github.com/flutter-devs/5fea39e0f237d7c170c9b4881fb9449a#file-colors-dart

Open strings.dart and add the following code.

https://gist.github.com/flutter-devs/3ea5eb95345260d66d2b59b32515337b#file-strings-dart

Open cardItem.dart and add the following code. It contains some basic information about a single item in the list.

https://gist.github.com/flutter-devs/b3b69439c3ae5e825a4a649a523a38c8#file-carditem-dart

Open constants.dart and add the following code. It contains variables for routes and some static content for the list items.

https://gist.github.com/flutter-devs/ffcbef6e9f40fcac4b6a81d9ba881778#file-constants-dart

Open data.dart and add the following code.

https://gist.github.com/flutter-devs/5d80446a82d9598a4eb6083d45d09e31#file-data-dart

  • At line 1, I extended our class with ChangeNotifier so that it can listen for changes.
  • Then, I have created some variables like successDrop (used to check whether Draggable is dropped into DragTarget or not), items (list of items which will be shown as Draggables ) and acceptedData (data accepted by DragTarget from Draggable).
  • At line 6, inside the constructor, initialize the list and variables.
  • Then I have created some getters and setters for the variables and inside setter functions notifyListeners() will be called so that the Widgets listening for these variables can rebuild.
  • At line 30, removeLastItem() method is created which will remove the last item from the list of Draggable.
  • At line 35, addItemToList() method is created which will add the particular CardItem into the list of DragTarget.

Now, open home.dart which will contain the HomePage of the app, and add the following code.

https://gist.github.com/flutter-devs/bc4e28ac4715dbb01d63613f85995ef2#file-home-dart

  • It contains FAB for Reset functionality and the Column widget at the center of screen having two childs : CardStackWidget() and DragTargetWidget() .
  • CardStackWidget (contains a list of Draggable) and DragTargetWidget (as the name suggests, contains DragTarget) I’ll be building later in this blog, Let me first explain this code a little bit.
  • At line 10, inside onPressed of FAB, I am calling initializeDraggableList() function which is present in data.dart class, so that our app can change to reset mode.
  • At line 11, I am calling changeSuccessDrop() function which is present inside data.dart as well, and passing the false value as initially no items were dropped on DragTarget.

Now, create a new file named cardStackWidget.dart and inside this add the following code.

https://gist.github.com/flutter-devs/02c67b7cb50ef0415f61ec55e96893d1#file-cardstackwidget-dart

  • Firstly, you will see the errors in line 29 because of DraggableWidget class, I’ll build this class later, but for now, let’s understand this code.
  • This widget contains the Stack and inside the children property, I am calling the function named cardItems() which returns the list of Widgets based on some condition.
  • At line 13, if the length of the list containing Draggable is less than 1 or empty it will return the Container showing ‘No Items Left’ so that it cannot be further dragged and user get to know about the end of the list.
  • At line 26, if the length is more than or equal to 1 then loop through the elements of the list and pass the particular item to DraggableWidget() which I’ll build later in this blog.
  • After this add the value of cardItemDraggable to list of widgets and return that list to the children of Stack.

Now create a new file named draggableWidget.dart and inside this add the following code.

https://gist.github.com/flutter-devs/757cf2b94328621d94fa80f166af7e8e#file-draggablewidget-dart

  • Firstly, this file is only responsible for building the Draggable widget for the particular index of CardItem list that I passed from CardStackWidget, so don’t get confused, I’ll explain the whole code.
  • At line 16, I passed the single item of list i.e single CardItem as the data of Draggable.
  • When the card is dragging, the previous card should be displayed in place of that card, so I’ll be doing this inside childWhenDragging property.
  • At line 24, for the color of the card if the index is more than or equal to 1 then color should be shown of the previous card that’s why I have written “(itemList.length-1)-1” and if the value of the index is less than 1 or 0 then simply set the grey color for the card.
  • At line 33 , same logic is applied for the content of the card if the index is more than or equal to 1 then set the content of previous card (this is done using elementAt() method, it returns the value at the index passed in the parameter ) in the Text widget and if the value of index is less than 1 or 0 then simply set the text as “No items left” .
  • At line 41, for feedback property, card at the index which I am getting from cardStackWidget is returned.
  • At line 56, for child property, card at the index which I am getting from cardStackWidget is returned.
  • Just for reminding: Data of Draggable can be accessed inside onWillAccept and onAccept property of DragTarget which will be present inside DragTargetWidget class and I have not built this class yet.

Summary

In our column, there were two children- CardStackWidget and DragTargetWidget and inside CardStackWidget there is DraggableWidget, I have built CardStackWidget and DragTargetWidget till now, Now it’s time to build DragTargetWidget.

Create new file named dragTargetWidget.dart and add the following code.

https://gist.github.com/flutter-devs/33dc55d35b7568a3e5d24ec243182711#file-dragtargetwidget-dart

  • This class is only responsible for building DragTarget. I’ll explain this whole code.
  • Firstly, I’ll take a look at builder function, at line 21, if the value of successDrop is false then simply return card having text “Drop Items here” wrapped around DottedBorder.
  • At line 4, inside onWillAccept function, return true, so that control gets transferred to onAccept function.
  • At line 7, the inside onAccept function I am calling three methods because :
  • 1) removeLastItem(): When Draggable is dropped on DragTarget then the last item from the list of Draggable should be removed.
  • 2)changeSuccessDrop(): When Draggable is successfully dropped on DragTarget the value of successDrop should be changed from false to true.
  • 3) changeAcceptedData() : Data accepted by DragTarget should be changed.
  • Now, at line 13 inside builder function I am checking if the value of successDrop is true then simply return the Stack containing the list of DragTarget as a children which are provided by a method called buildTargetList() taking the acceptedData as a parameter.
  • At line 51, inside buildTargetList() function simply add a card wrapped around DottedBorder containing the content of acceptedData to the list.

That’s the end of the article, you can run the app on your device or emulator to see the output.

Link of the code :

flutter-devs/flutter_dragdrop_demo
A flutter sample app to showcase drag-drop functionality in flutter. – flutter-devs/flutter_dragdrop_demogithub.com

Interesting part of this app is , I am not using Stateful Widget , instead I am using Provider package.

I got something wrong? Mention it in the comments. I would love to improve.

If you learnt even a thing or two, clap your hands 👏 as many times as you can to show your support!

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 FacebookGitHubTwitter, and LinkedIn for any flutter-related queries.

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

Related: SMS Using Twilio In Flutter

Related: Using SharedPreferences in Flutter

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


Plugins in Flutter | Plugins created by FlutterDevs

The road to cross-platform app development has been jam-packed lately, the main reason being its alluring nature of single codebase where developers have to write code once and that code can be used to develop apps for different platforms. I know! This is fun as,

  1. Single Codebase
  2. Reduced Development time
  3. Reduced Development Cost

and of course, there are disadvantages too, no doubt.

Flutter is the latest entry to the cross-platform app development, developed by Google and it’s gaining popularity day by day standing strong against its other competitors because of certain factors:

  1. Development Time
  2. Runtime performance
  3. Good tooling support

However, apart from the various merits that it had established there are few demerits, one being Limited set of libraries.
Even though Flutter is backed by Google but being a relatively new framework it lacks support for 3rd party frameworks and any cross-platform environment depends on the native platform features such as Camera, Bluetooth, Location, etc. which can be accessed using Plugins.

Plugins?

Plugins are the wrapper of the native code like android(java or kotlin) and iOS(swift or Objective C). Plugins are written in platform-specific code to access the platform-specific features.

Flutter does support using packages and plugins contributed by other developers to its ecosystem. You can access Flutter packages and plugins from here.

How do things work underneath the hood?

Flutter’s platform specific API depends on message passing technique, this takes place in two steps. Firstly, Flutter uses the Platform channel as the medium to communicate between the Flutter app and host, the host being the iOS or Android part of the app. Secondly, the host receives the messages through the Platform channel and then it invokes the platform-specific APIs using the native programming language of the platform and sends back the feedback to the Flutter app asynchronously.

In detail, on the client side, the MethodChannel is used to send the messages and on the host side, MethodChannel on Android and FlutterMethodChannel on iOS is used to receive and send messages. All of this is done to make sure that the least amount of boilerplate code is used.


Plugins developed by FlutterDevs team:

The team at FlutterDevs had developed their own plugins of basic day to day needs like an image plugin which picks the images from the storage called image_galley, a QR plugin which scans and generates qr code, a camera plugin, and a location plugin, let’s see about them in detail:

image_gallery:

A flutter plugin to show all your images from the storage. You can get the plugin from here.

usage:

Future<void> loadImageList() async {
List allImageTemp;
allImageTemp = await FlutterGallaryPlugin.getAllImages;


setState(() {
this.allImage = allImageTemp;
});
}

qr_utils:

A flutter plugin to generate and scan QR codes. This plugin can be used to scan 1D barcode and 2D QR code. You can get the plugin from here.

usages:

  1. Scan QR
final content = await QrUtils.scanQR;

2. Generate QR

Image image = await QrUtils.generateQR(content);

camera_utils:

A flutter plugin which does various works for you, it helps capture an image, pick an image, capture a video, pick a video and pick thumbnail from a video. You can get the plugin from here.

usages:

  1. Capture an Image
final path = await CameraUtils.captureImage;

2. Pick an Image

final path = await CameraUtils.pickImage;

3. Capture a Video

final path = await CameraUtils.captureVideo;

4. Pick a Video

final path = await CameraUtils.pickVideo;

5. Pick a thumbnail from a video

Future<String> thumbPath = CameraUtils.getThumbnail(path);
thumbPath.then((path) {
setState(() {
_thumbPath = path;
print(path);
});
});

geo_location_finder:

A flutter plugin to get an accurate location on Android and iOS devices. You can get the plugin from here.

usages:

Future<void> _getLocation() async {
Map<dynamic, dynamic> locationMap;

String result;

try {
locationMap = await GeoLocation.getLocation;
var status = locationMap["status"];
if ((status is String && status == "true") ||
(status is bool) && status) {
var lat = locationMap["latitude"];
var lng = locationMap["longitude"];

if (lat is String) {
result = "Location: ($lat, $lng)";
} else {
// lat and lng are not string, you need to check the data type and use accordingly.
// it might possible that else will be called in Android as we are getting double from it.
            result = "Location: ($lat, $lng)";
}
} else {
result = locationMap["message"];
}
} on PlatformException {
result = 'Failed to get location';
}

if (!mounted) return;

setState(() {
_result = result;
});
}

These are some of the plugins generated by FlutterDevs. If you wanna create a plugin by yourself then you might want to read this article to walk you through the process of creating a plugin.

Creating a Flutter Plugin for Android and iOS | Image Gallery
Flutter plugin is the wrapper of the native code like android( Kotlin or java) and iOS(swift or objective c)…flutterdevs.com

I hope you liked the article and if you wanna convey something, be it a mistake then feel free to send the feedback in the comments.

Read other articles:

Developing Web Apps Using Flutter | Flutter for Web
Flutter was introduced back in May 2017 with the general idea of Cross-Platform app development initially for Android…medium.com

From Our Parent Company Aeologic

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

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

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

Related: Developing Web Apps Using Flutter

Related: Flutter App for Desktop

Related: Cupertino (iOS-style) ActionSheet in Flutter | Know Your Widgets

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