Google search engine
Home Blog Page 33

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.


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.


Developing Web Apps Using Flutter

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.

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.