Google search engine
Home Blog Page 33

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.


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.

Example Animations in Flutter — #2

0

Introduction

In this blog, we’re going to implement some examples of basic animations in Flutter. In the previous article, I explained some basic concepts of animation which needs to be understand before diving into animation. So, if you want to understand those concepts of animation, head over to that article.


Let’s Start

First, we’ll see very simple rotation animation.

Create home_screen.dart file and copy the following code inside it

https://gist.github.com/flutter-devs/383d3c50b4d8ec79a5bacd55566f9beb#file-home_screen-dart

In initState() method, _arrowAnimationController is initialised with duration of animation equal to 300 milliseconds.

After that, _arrowAnimation is initialise with begin value of 0.0 and end value of pi (value = 180) so that, it will rotate by 180 degrees.

Now, comes the layout part of the screen, paste the following code inside build() method

https://gist.github.com/flutter-devs/2473e9cc9cf4c2e139e177ca7790566b#file-home_screen-dart

Now, let’s create firstChild() Widget, where the actual widget will be present that contains a widget that needs to be animate and another widget that starts the animation.

https://gist.github.com/flutter-devs/43b76678d571495574a857b834bc8e7c#file-home_screen-dart

In the given code, first child of Row is Icon that needs to be animated and it is wrapped with AnimatedBuilder widget.

AnimatedBuilder widget is a widget that is useful for building animations. It is more effective and efficient way of animating any Widget than calling setState() method on each change in value of animation.

2 properties of AnimatedBuilder widget are specified in the given code —

  • animation — It expects a animationController that is responsible for controlling animation. In this case, we’ve specified _arrowAnimationController which controls the arrow animation which we’re implementing
  • builder — It’s a callback function which is called everytime the value of animation changes. In the builder function, we’re returning Icon widget which is wrapped with Transform.rotate() widget.

Transform.rotate() widget is a special type of widget that transforms its child using a rotation with respect to center using its angle property which specify the angle by which the widget needs to be rotated

Now, another widget in the Row is OutlineButton which is used for starting the animation. In the onPressed() callback, we’re checking if the given animation is completed, and, if the button is again clicked, then the animation is reversed else just start the animation in forward direction

Now, let’s see a beating heart animation…

https://gist.github.com/flutter-devs/f0243fffac2d4a5fdc349336090fe01b#file-home_screen-dart

In home_screen.dart file, create two more variables _heartAnimation and _heartAnimationController of Animation and AnimationController respectively.

Inside initState() method, _heartAnimationController is initialised with duration of 1200 milliseconds. After that, _heartAnimation is initialised with the begin and end value of 150.0 and 170.0 and then, CurvedAnimation is specified with bounceOut curve, so that, the heart icon will show some bouncing effect

And atlast, we’re attaching the statusListener with _heartAnimationController, and checking if _heartAnimation is completed, then, we’re repeating the animation.

Now, we’ll attach this animation with a heart icon

https://gist.github.com/flutter-devs/89e362502fef09502479896e3f006268#file-home_screen-dart

Inside, secondChild() widget, first child of Row is heart icon on which we’ve to show animation. It is wrapped with AnimatedBuilder widget so that it will animate according to the given animation. In the size of Icon, _heartAnimation.value is specified which means that as soon as the value of _heartAnimation changes, size of icon will also change with the _heartAnimation value.

Second child of Row is OutlineButton which is responsible for starting the heartAnimation. And finally, override dispose() method, and dispose both AnimationController objects.

https://gist.github.com/flutter-devs/77a412b8927fc7c7c53ef2a9f3ec3710#file-home_screen-dart

Now, let’s move on to another animation which is a little bit complex…

Inside home_screen.dart file, add another OutlineButton which is responsible for navigating to another screen where we’ll see another beautiful animation.

https://gist.github.com/flutter-devs/9dbb73e4997b17d6cb846fb34a50483c#file-home_screen-dart

Inside AnimatedScreen class, we’ll create these two animations

  • Let’s create the first animation…

In both these animations, 3 animations are happening simultaneously —

  • First, Container size is increasing
  • Second, Container radius is changing
  • Third, Container colour is changing

Paste the following code inside AnimatedScreen class –

https://gist.github.com/flutter-devs/1e3fe5e5b266e7870c688c58dd4d7037#file-home_screen-dart

Declare 3 Animation objects — _containerRadiusAnimation, _containerSizeAnimation, _containerColorAnimation and one AnimationController object — _containerAnimationController

Inside initState() method, _containerAnimationController is initialised with the duration of 5 seconds.

After that, _containerRadiusAnimation is initialised with BorderRadiusTween which interpolates between two BorderRadius values. Here, in begin value BorderRadius of Container is 100.0 so that initially it appears as a circle and in end value BorderRadius of Container is 0.0, so that at last, it appears as a rectangle. And finally we’re attaching _containerAnimationController with _containerRadiusAnimation.

Now, _containerSizeAnimation is initialised with Tween which interpolates between two double values. Here, begin value is 0.0 so that the size of Container remains 0.0 initially and end value is 2.0. And finally we’re attaching _containerAnimationController with _containerSizeAnimation.

Now, _containerColorAnimation is initialised with ColorTween which interpolates between two Color values. Here, in begin value Color of Container is black and in end value Color of Container is white. And finally we’re attaching _containerAnimationController with _containerColorAnimation.

And finally, we’re starting the animation.

Now, let’s attach the animation with the Container…

https://gist.github.com/flutter-devs/5614a44031e44c896af5256e9ff362d4#file-animated_screen-dart

AnimatedBuilder is specified in the body of Scaffold and in the builder callback, Container is returned. In the transform property, Translation matrix is specified and value of x-coordinate is _containerSizeAnimation.value * width which means that initially, the x coordinate will be 0.0 and atlast, value of x coordinate will be 2 * (screenWidth) — 200.0 and value of y and z coordinate is 0.0 which means that it’ll only change it’s x coordinate (move horizontally).

Width and height of Container is _containerSizeAnimation.value * height which means that it’ll gradually increase it’s size. At last, value of borderRadius is _containerRadiusAnimation.value which means that borderRadius of Container will decrease from 100.0 to 0.0

That’s all, This will create the following animation

Now, to create second animation, just remove the transform property of Container and see the effect. That will create following animation.

Complete code is available here

https://github.com/flutter-devs/flutter_animation_example


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.


Functional Error Handling In Flutter

0

The Dart language offers natives like try, catch, and throw for dealing with errors and particular cases in our applications.

This blog will explore the Functional Error Handling In Flutter. We will learn how to execute a demo program and understand error handling by learning Either type from the fpdart package 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 Functional Programming?

Demo: Parsing a Number

Either type

Comparing Either and Result

Either & the tryCatch Factory Constructor

Conclusion



What is Functional Programming?

Functional programming (or FP) is an intriguing point that advances utilizing pure functions, immutable data, and a revelatory programming style, assisting us with composing all the more perfect and viable code.

This is rather than object-arranged programming (OOP), which depends on variable states and a basic programming style to depict the information and conduct of the items in our framework.

Since numerous advanced languages support both functional and object-situated ideal models, you can take on one style or the other as you see fit in your code.

In fact, you may have already used FP in your Dart and Flutter code by:

  • passing a function as an argument to another capability, (for example, a > callback)
  • utilizing the map, where, reduce functional operators on Iterable sorts like list and streams
  • working with generics and type inference

Demo: Parsing a Number

If we have any desire to parse a String containing a numerical value into a double, we can compose code like this:

final value = double.parse('155.50');

However, what would happen if we tried running this?

final value = double.parse('not-a-number'); 

This code throws an exception at runtime.

In any case, the mark of the parse function doesn’t let us know this, and we need to peruse the documentation to find out:

static double parse(String source);

If we want to handle the FormatException, we can use a try/catch block:

try {
final value = double.parse('not-a-number');
// handle success
} on FormatException catch (e) {
// handle error
print(e);
}

However, on large codebases, it’s challenging to figure out what abilities could throw and which don’t.
Ideally, we accept the signature of our functions ought to make it unequivocal that they can return an error.

Either type:

Either type from the fpdart package allows us to determine both the disappointment and achievement types as a component of the capability signature:

import 'package:fpdart/fpdart.dart';

Either<FormatException, double> parseNumber(String value) {
try {
return Either.right(double.parse(value));
} on FormatException catch (e) {
return Either.left(e);
}
}

The values inside Either. left and Error. right should match the sort explanations we have characterized (FormatException and double for this situation). Continuously use Either. left to represent errors, and Either. right to represent the return esteem (achievement).

Comparing Either and the Result:

From the beginning, Either is the same as the Result type that is accessible in the multiple_result package:

Result<FormatException, double> parseNumber(String value) {
try {
return Success(double.parse(value));
} on FormatException catch (e) {
return Error(e);
}
}

In fact, only the basic syntax changes:

  • Either.right ↔ Success
  • Either.left ↔ Error

But Either has a much more extensive and powerful API.

Either & the tryCatch Factory Constructor:

If we have any desire to improve on our execution, we can utilize the tryCatch factory constructor:

Either<FormatException, double> parseNumber(String value) {
return Either.tryCatch(
() => double.parse(value),
(e, _) => e as FormatException,
);
}

This is how tryCatch is implemented:


factory Either.tryCatch(
R Function() run, L Function(Object o, StackTrace s) onError) {
try {
return Either.of(run());
} catch (e, s) {
return Either.left(onError(e, s));
}
}

Note that the onError callback gives the error and stack trace as arguments, and the error type is Object.

But since we know that the double.parse the function can only ever throw a FormatException, it’s safe to cast e as a FormatException in our parseNumber function.

Conclusion:

I hope this blog will provide you with sufficient information on Trying Functional Error Handling In Flutter. We’ve now ventured into the world of functional programming, by learning about Either and the fpdart package.

  • we can utilize Either<L, R> as an option in contrast to throwing exceptions at whatever point we need to proclaim mistakes expressly in the mark of our capabilities/strategies.
  • If we use Either and don’t deal with errors, our code will not arrange. This is superior to finding errors at runtime during development.
  • Either accompanies a broad Programming interface, making it simple to control our data with a valuable practical operator like map, mapLeft, fold, and numerous others.

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


Bottom Navigation Bar using Provider | Flutter

In this article, I’ll be showing you how you can use Flutter Provider package in the BottomNavigationBar.

What is Provider?

Provider is a new state management approach recommended by the Flutter team.

Note
setState also works fine for many case , you should not use it every where .
But in case you have a messy code like you have a FutureBuilder in the build then setState will definately cause problem.

Let’s see how we can use it in BottomNavigationBar.

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

provider : <latest-version>

Step 2: Create a provider class

class BottomNavigationBarProvider with ChangeNotifier {
int _currentIndex = 0;

get currentIndex => _currentIndex;

set currentIndex(int index) {
_currentIndex = index;
notifyListeners();
}
}

In this provider, I am storing the current value of the BottomNavigationBar and when the current value is set into to provider, the BottomNavigationBar will be notified with the current value and update the tab.

Step 3: Wrap parent Widget with ChangeNotifierProvider

home: ChangeNotifierProvider<BottomNavigationBarProvider>(
child: BottomNavigationBarExample(),
builder: (BuildContext context) => BottomNavigationBarProvider(),
),

I have wrapped my widget with ChangeNotifierProvider so my widget will be notified when the value changes.

Step 4: Create tabs for BottomNavigationBar

/media/7d35f19dd026ff04c66dc5949141d9d6

I have three widgets tabs which I’ll attach with my bottom navigation bar.

Step 4: Create BottomNavigationBar with provider

/media/f685773a51366e2d6cf18b838fa21e07

So I have created a list for the screens and change the screens with an index which is provided by the provider and the tab changes the provider updates the index.

Here is the code for the above example :

flutter-devs/Flutter-BottomBarProvider
A sample application for bottom bar using Provider. – flutter-devs/Flutter-BottomBarProvidergithub.com

Persistent BottomNavigationBar

Provider works great when changing the tabs without using setState but if you want to keep your state of the screens attached with the tabs, try using PageStorageBucket , I have attached an example by Tensor Programming below:

tensor-programming/flutter_presistance_bottom_nav_tutorial
Contribute to tensor-programming/flutter_presistance_bottom_nav_tutorial 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. We would love to improve.

Clap 👏 If this article helps you.

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.


Firebase ML Kit in Flutter — Part 1

0

Firebase is basically a mobile and web application development platform used to help in building high-quality apps.

Flutter is basically a mobile application development framework used to build apps for both Android and iOS from a single codebase.

Firebase provides a variety of products such as realtime-database, cloud storage, ML Kit, etc. and we can integrate them in Android, iOS and Flutter application. So in this series, I will cover how to integrate Firebase ML Kit in your Flutter application. But first of all, let’s see how to setup Firebase in your Flutter app (for both Android and iOS).

Firebase Setup:

  1. Create a new project in Firebase console.

2) After your project is ready, the following screen will appear in the console, if you want to setup firebase for your Android app then click on Android icon else click on iOS icon for the iOS application. In this blog, we will set up for both platforms.

In order to add firebase to your project, you first need to create a new flutter application. Open your terminal and copy the following command for creating a new flutter project. Here “mlkit_demo” is the name of a project.

Setup for Android app :

  • After clicking on Android icon in firebase console, you will see the following screen, In order to add Firebase in your Android app, you will need app’s package name and SHA-1 certificate.
  • For app’s package name, open your flutter application and inside this go to “android/app/src/AndroidManifest.xml”.
  • For SHA-1 certificate, copy the following command. After writing this command it will ask for the keystore password, the password is: “android
  • After registering your app with firebase, download “google-services.json” file and copy this file inside the “android/app” directory.
  • Now, add some Google services and firebase dependencies to your Android app.

That’s it for Android. Now we’ll set up for iOS app.


Setup for iOS app :

  • After clicking on the iOS icon in the console, you will see the following screen. In order to add Firebase in your iOS app, you will need iOS bundle ID, in case of iOS, it doesn’t matter that you have to write only the app’s package name instead you can give any name to it. For this project, I am giving it as “mlkit.demo”.
  • After registering your app with firebase, download “GoogleService-Info.plist” file and copy this file inside “ios/Runner” directory.

That’s it for iOS as well, Now I will add some packages to our flutter app that we created earlier in this blog.


Open “pubspec.yaml” file from your flutter app and add the following package inside it. After adding this, get your packages.

firebase_ml_vision:

That’s it from this blog, in the next part of the series I will show you some of the exciting features of Firebase ML Kit.


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.


Developing packages in Flutter

Introduction

In this blog, I’m going to show you how to develop a package in Flutter and upload it to pub.dev

Let’s Start

Open up the Android Studio and select Start a new Flutter project and then, a dialogue will open. In this dialogue, select Flutter package option as shown in the below images

Now, enter all the details of your package such as package name, project location, and package description. In this blog, we’re gonna create a custom switch, so give the package name as “custom_switch”

Now, your project is created. Delete the boilerplate code that is created as part of the project

Create a stateful widget class and name it CustomSwitch and include the SingleTickerProviderStateMixin in this class as shown below.

https://gist.github.com/flutter-devs/d2d21e3911c40cb624e48ba5f8fb21a2#file-custom_switch-dart

In the above code, we’re also declaring 3 member variables —

  • value — This is the value of our switch. If switch is ON then value will be true else value will be false
  • onChanged — This is the void callback which is used to change the value of switch from true to false and vice-versa
  • activeColor — This is the color shown when the switch is ON

Now, add the following code inside _CustomSwitchState class

https://gist.github.com/flutter-devs/e585ff4ae3f76881345795b25c7cc53c#file-custom_switch-dart

_circleAnimation and _animationController objects are created of type Animation and AnimationController respectively.

In initState() method, the _animationController object is initialized with a duration of 60 milliseconds. After that, _circleAnimation is initialized with AlignmentTween, because as shown in the thumbnail image, alignment of a white circle inside the switch is changing on every change in the value of the switch

In the begin value of AlignmentTween, we’re checking, if the value of the switch is true, then the Alignment will be centerRight else the Alignment will be centerLeft and at last, we’re attaching the animationController with this animation with Linear curve.

Now, paste the following code inside build() method —

https://gist.github.com/flutter-devs/9b235f7597f595c91b41953574cefa30#file-custom_switch-dart

In the following code, AnimatedBuilder widget is returned which means that it helps to animate its descendant widgets. Inside this, Container of width 70.0 & height 35.0 is returned. In the color property of Container, we’re checking if the alignment of white circular container is centerLeft(Switch OFF), then the color would be grey else color would be activeColor.

Now, in the child of Container, Row widget is returned. In the case of first children of Row, we’re checking if the alignment of a white circular container is centerRight (Switch ON) then, “ON” text will be displayed else an empty Container.

In the case of second children of Row, we’re adding the white circular Container and wrapping it with Align widget and in the alignment property, the value of _circleAnimation is given which means as soon as the value of _circleAnimation changes, alignment of white container changes.

In the case of third children of Row, we’re checking if the alignment of the white circular container is centerLeft (Switch OFF) then, “OFF” text will be displayed else an empty Container.

Now, the last step is to apply gestures on Switch. Wrap the root Container with GestureDetector widget and in the onTap() method paste the following code

https://gist.github.com/flutter-devs/85ebd7bd8da22b8f7e6e2bfca62b1474#file-custom_switch-dart

In this, we’re checking if the current playing animation is completed, then, simply reverse it else, forward it. And, if the value of switch is false, then we’re changing it’s value to true using onChanged() VoidCallback which we’ve defined in above steps else, we’re changing the value to false.

That’s all, now the CustomSwitch class is completed. Now, let’s create an example app which will use this package to display a switch in the app.

Create a new flutter project and name it “example” and to use “custom_switch” package in this project before uploading it to pub.dev, add the following code inside pubspec.yaml file —

https://gist.github.com/flutter-devs/0936c24a24fbdd4d62e6353085603804#file-pubspec-yaml

Now, go to main.dart file, and paste the following code inside it —

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

  • In line 1, we’re importing the custom_switch package.
  • In line 27, bool variable is initialised with the initial value of false, so that initially switch remains off
  • In line 39, CustomSwitch widget is added. Active color of switch is given as pinkAccent, value property is given the value of status variable and in onChanged() callback, value of status variable is changed with the value parameter of onChanged() callback
  • In line 50, Text widget is added and value of status variable is given as it’s text.

Now, run the app and you’ll see the following output —

Now, we’ve successfully added the code for CustomSwitch package. Now, let’s see what all other details are required to be added to publish the package to official packages directory.

In the pubspec.yaml file, you are required to add following details — name, description, version, author & homepage

https://gist.github.com/flutter-devs/34d524043698eec1657b6269911e9d76#file-pubspec-yaml

At last, you have to run one command that is used to check if our package has any warnings or not, whether it can be published or not? So, paste the following code inside the terminal window —

Now, press Enter and it will tell if there is any warnings in our package or not. In our case, it has 0 warnings

Finally, upload the package using the following command and your package will display on the official packages directory (It will take some time to display your package on the official packages directory)

Package Link — https://pub.dev/packages/custom_switch


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

If you learned even a thing or two, clap your hands 👏 as many times as you can to show your support! This motivates me to write more.

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.


Creating a Countdown Timer using Animation in Flutter

0

In this article, I will be building a count down timer with the help of the animation and using custom paint.

First of all, create an app which returns the MaterialApp.

Now create a new Widget CountDownTimer and make sure that it must be a Stateful Widget because we are using animation and we will need to add TickerProviderStateMixen .

class CountDownTimer extends StatefulWidget {
@override
_CountDownTimerState createState() => _CountDownTimerState();
}

class _CountDownTimerState extends State<CountDownTimer>
with TickerProviderStateMixin {
}

Create an Animation Controller

Create an animation controller and initialise it in initState() .

AnimationController controller;

@override
void initState() {
super.initState();
controller = AnimationController(
vsync: this,
duration: Duration(seconds: 5),
);
}

I am right now using only 5-second duration for my animation to happen.

Create a Circular progress bar using Custom paint

Create a class which extends CustomPainter

class CustomTimerPainter extends CustomPainter

Add properties

Now we will need some properties so we can customize my custom painter class from my widgets screen.

class CustomTimerPainter extends CustomPainter {
CustomTimerPainter({
this.animation,
this.backgroundColor,
this.color,
}) : super(repaint: animation);

final Animation<double> animation;
final Color backgroundColor, color;
}

I am using background color and color property for my Circular progress bar and to animate my progress bar, I will need an animation.

Override methods

We will override our paint method which will use to paint our circular progress bar.

First, we will paint a circle and we will create an arc will move around the circle.

In the paint method, create a Paint object and add properties.

Paint paint = Paint()
..color = backgroundColor
..strokeWidth = 10.0
..strokeCap = StrokeCap.butt
..style = PaintingStyle.stroke;

Now draw a circle

canvas.drawCircle(size.center(Offset.zero), size.width / 2.0, paint);

When the circle is painted then will need to draw an arc to move.

paint.color = color;
double progress = (1.0 - animation.value) * 2 * math.pi;
canvas.drawArc(Offset.zero & size, math.pi * 1.5, -progress, false, paint);

Change the color of the paint and update the process using the current animation value and draw the arc.

Now we also have an override method shouldRepaint .

@override
bool shouldRepaint(CustomTimerPainter old) {
return animation.value != old.animation.value ||
color != old.color ||
backgroundColor != old.backgroundColor;
}

Here is the code for the CustomTimerPainter class

https://gist.github.com/flutter-devs/cc42bd1506770b35025b59afd493e203#file-customtimerpainter-dart

Create the UI

To animate my Custom Progress bar we will wrap my an AnimatedBuilder and provide the animation and it returns a CustomPaint Widget. When My animation will start the value of the arc will update in the custom painter class and update the UI

AnimatedBuilder(
animation: controller,
builder:
(BuildContext context, Widget child) {
return CustomPaint(
painter: CustomTimerPainter(
animation: controller,
backgroundColor: Colors.white,
color: themeData.indicatorColor,
));
},
),

And to start and pause the animation Ill use the Floating Action Button, we have also Wrapped my FAB with AnimatedBuilder so we can update my play and pause status.

AnimatedBuilder(
animation: controller,
builder: (context, child) {
return FloatingActionButton.extended(
onPressed: () {
if (controller.isAnimating)
controller.stop();
else {
controller.reverse(
from: controller.value == 0.0
? 1.0
: controller.value);
}
},
icon: Icon(controller.isAnimating
? Icons.pause
: Icons.play_arrow),
label: Text(
controller.isAnimating ? "Pause" : "Play"));
}),

Now if we see the app, it will look like this

Now Wrap the CustomTimerPainter inside the Stack and add text to represent the value.

https://gist.github.com/flutter-devs/8b8a56051de58b44f0997270d76aa037#file-countdowntimer-dart

To convert the animation duration into time String.

String get timerString {
Duration duration = controller.duration * controller.value;
return '${duration.inMinutes}:${(duration.inSeconds % 60).toString().padLeft(2, '0')}';
}

Here is the code of CountDownTimer Widget

https://gist.github.com/flutter-devs/fb872f913be7aaddab061493b3988c59#file-countdowntimer-dart

I have wrapped the root body widget and added a new Container and animating with animation value.

Container(
color: Colors.amber,
height:
controller.value * MediaQuery.of(context).size.height,
),

Here this complete code

flutter-devs/CountDownTimer
Contribute to flutter-devs/CountDownTimer 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.

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.


How to manage States in Flutter using Redux

In Flutter there are many state management techniques and one of them is Redux. Generally Redux is a unidirectional data flow architecture that helps a developer to develop and maintain an App easily

Redux is designed elegantly so the user can easily interact with the App which has frequent state changes, here are the four components generally Redux contains.

  1. Action: When an event is generated then it is represented as an action and is dispatched to the Reducer.
  2. Reducer: When Reducer gets any update, it updates the store with a new state what it receives.
  3. Store: When Store receives any update it notifies to the view.
  4. View: It is recreated to show the changes which have been made.

In the above-mentioned process, the main thing which plays a vital role we fetch any third-party data is Redux Middleware, so here a question arrives what is middleware and what it does ??

Redux Middleware

When Application performs any operation like fetching any data from third-party API then middleware comes into action it manages data when it is dispatched from the action and before it reaches the reducer.

If we talk about the functioning of Redux, it works generally in two different ways which are used in any Basic App.

  1. When all the states are held in a single Store: developers can access the Stored States which is having all the data changes we need, and if we need to update state all the app will get to know.
  2. When data flows Unidirectionally: Data Flow is unidirectional and hence the data flow and handling of data become easier and the process containing all four steps which have already been mentioned earlier.

Now it is high time to understand it by an example, so here we are going to demonstrate it by a shopping cart app where we would select items into cart and remove them according to our choices.

How to use Redux in Flutter?

Before using Redux, you should know that flutter SDK does not have support for Redux but by using the flutter_redux plugin, it can be implemented.

Implementation

Step 1: Add the dependencies

Add dependencies to pubspec.yaml file.

Dependencies:

flutter_redux:
redux:

Here redux provides the architecture for the App and flutter_redux provides the store provider to manage the App.

Step 2: Import

import 'package:redux/redux.dart';
import 'package:flutter_redux/flutter_redux.dart';

And after this, we go to the implementation part of redux so first,

Wrap Material app with store provider, it is a base widget that will pass the given Redux store to all descendants that request it.

https://gist.github.com/shivanchalpandey/5705bc626dbfcd13feb7be17505d6c2f#file-main-dart

Then we create a list of items that we would add or remove

https://gist.github.com/shivanchalpandey/7326e126f2ac7e040bff3b181903e804#file-cartlist-dart

Here we have created a list in which the ListTile is having a text and an icon by which we would handle its functioning of adding or removing it to a cart list.

Now we will define a list of items in AppState class which is having both the cart Item list and main Item list.

https://gist.github.com/shivanchalpandey/c7a03f565848d380b8d6f288a4ef6b48#file-appstate-dart

It will manage states of actions and will dispatch it to reducer so here reducer plays the main role while it is being dispatched to the store.

https://gist.github.com/shivanchalpandey/3d9d95e408a4b4bdcd077285571adced#file-reducer-dart

Here in reducer class actions are being performed like adding or removing items from the cart list and main list.

Now we have to link our states which are being created to the state connector and hence it will manage all the changes we have made,

By this approach, we will connect our whole app with the states that are dispatched to the app and we can access this anywhere in the app.

So it is the full description of the Redux.


Thanks for reading this article

If You find something wrong? Let me know in the comments. I would love to improve.

Connect with me on GitHub repositories.


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 has been working on Flutter for quite some time now. You can connect with us on Facebook and Twitter for any flutter related queries.

Implement searching with Firebase firestore | Flutter

0

Hi Everyone, In this article, I am going to show you how to search for a document in a collection.

What is the need?

Suppose we have a list of documents inside a collection and we want the search in the document list with respect to caseNumber

What do I have?

Query where(
String field, {
dynamic isEqualTo,
dynamic isLessThan,
dynamic isLessThanOrEqualTo,
dynamic isGreaterThan,
dynamic isGreaterThanOrEqualTo,
dynamic arrayContains,
bool isNull,
}){

}

Should I use isEqualTo?

List<DocumentSnapshot> documentList;
documentList = (await Firestore.instance
.collection("cases")
.document(await firestoreProvider.getUid())
.collection(caseCategory)
.where("caseNumber", isEqualTo: query)
.getDocuments())
.documents;

if you use isEqual then you will have to write the whole query, In my case, I will have to write the whole caseNumber to display the search result.

Or isGreaterThanOrEqualTo?

Flutter firestore plugin also allows searching for particular data in the document.

documentList = (await Firestore.instance
.collection("cases")
.document(await firestoreProvider.getUid())
.collection(caseCategory)
.where("caseNumber", isGreaterThanOrEqualTo: query)
.getDocuments())
.documents;

But you will not be satisfied with the result.

Source (Stack overflow)

What I really want?

Even if I type a single alphabet fo the search query I should get the most appropriate result from the firestore.

What should I do?

You will need to add the list of query options that a user will search for.

For example

For caseNumber (1011222) , user can search

[1 , 10 , 1011 , 10112 , 101122 , 1011222]

At the time when you are pushing data into the firestore you can do is to create the search query options.

{

"caseSearch": setSearchParam(caseNumber),

}

To add the list of query options

setSearchParam(String caseNumber) {
List<String> caseSearchList = List();
String temp = "";
for (int i = 0; i < caseNumber.length; i++) {
temp = temp + caseNumber[i];
caseSearchList.add(temp);
}
return caseSearchList;
}

This will result in pushing all the queries that a user can search for.

Implement

In the TextField, when text value is changing, it is quiring in the database

onChanged: (String query) {

getCasesDetailList(query);

}

Now we have the arrayContains in the query, all you need to do is check for the text value that is being typed and it firebase query will automatically search all the documents which have the caseSearch an array that contains the query.

List<DocumentSnapshot> documentList = (await Firestore.instance
.collection("cases")
.document(await firestoreProvider.getUid())
.collection(caseCategory)
.where("caseNumber", arrayContains: query)
.getDocuments())
.documents;

Now you will get all the list of documents that matches the search query.


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.

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.