Google search engine
Home Blog Page 34

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.


Working with MobX in Flutter

T his article focus mainly on Mobx and how it’s handled in Flutter. We will be covering setState(), MobX & Redux and their association with React by getting a general Knowabouts about their inner workings. By the End of this Blog read, you might be able to Differentiate b/w Redux & MobX as State Management Technique for your flutter Apps .Without any further delay, Let’s get started:-

Everything in Flutter constitute of widgets. Widgets are the basic building blocks that can be reused at a later time. They can be Classified into — stateless(No internal state exist) & stateful(Dynamic) widgets .

What is basically this “State” ?

State is information that can be read synchronously when the widget is built and might change during the lifetime of the widget. It is the responsibility of the widget implementer to ensure that the State is promptly notified when such state changes,using State.setState which is useful mainly when State is heiharchical and matches component structure.

Though, SetState has its own limitations :

  • Share More state across components — Internal state management become troublesome when you need to share more states across components.
  • Distant leaf components need access to states — Intermediary components doesn’t need to know becomes a problem as data gets shared to all pass through components.

To prevent This ,

We manage Application state externally to component by either of:

  • Bloc
  • Rx model
  • Provider
  • Scoped model
  • MobX
  • Redux model

Where individual leaf component can Access and Manipulate state.

MOBX: STATE MANAGEMENT TECHNIQUE

"MobX is just a state-management library that makes it really simple to connect the reactive data of your application with the UI” .

Here is a quick list of the MobX features that together make it Indispensable for Flutter:-

  • It is Simple, Scaleable and Unobtrusive state management library that has been very effective library for the JavaScript apps and this also port to the Dart language aiming to bring the same levels of productivity.
  • MobX is a Battle tested state management library Transparently Functional Reactive programming (TFRP). The design principle is very simple:Anything that can be derived from the Application state, should be derived Automatically : UI, data serialization, server communication, etc.
  • MobX is a state-management library that makes it simple to connect the reactive data of your application with the UI. This wiring is completely automatic and feels very natural. As the Application-developer, you focus purely on what reactive-data needs to be consumed in the UI without worrying about keeping the two in sync.
  • It’s not really magic but it does have some smarts around what is being consumed (Observables) and where (Reactions) and automatically tracks it for you. When the Observables change, all Reactions are re-run these Reactions can be anything from a simple console log, a network call to re-rendering the UI.

React & MobX

React and MobX together are a Prominent combination. React renders the application state by providing mechanisms to translate it into a tree of renderable components whereas MobX provides the mechanism to store and update the application state that React then further uses.

Both React and MobX provide optimal and unique solutions to common problems in Application development. React provides mechanisms to optimally render the UI by using a virtual DOM that reduces the number of costly DOM mutations. MobX provides mechanisms to optimally synchronize application state with React components by using a reactive virtual dependency state graph that is only updated when strictly needed and is never stale.

Why MobX is a solid State Management architecture for Flutter:-

  • Firstly, It uses comparatively less boilerplate code needed to implement State Management in MobX for Flutter when compared to other techniques at disposal and once all the actions are put into place, how the events will turn out and which properties to update are mainly not of concern.
  • Easy Interoperability: MobX works with plain JavaScript structures. Due to its unobtrusiveness, It works with most JavaScript libraries out of the box without Needing MobX specific library add-ons. For the same reason, you can use it with both server and client side, isomorphic and react-native applications.The result of this is that you often need to learn fewer new concepts when using MobX in comparison to other state management solutions.
  • Using Classes and Real References: With MobX you don’t need to normalize your data. This makes the library very suitable for very complex domain models.
  • Referential Integrity Is Guaranteed :Since data doesn’t need to be normalized and MobX automatically tracks the relations between state and derivations, you get referential integrity for free.
  • Rendering Through Many Levels :No problem, MobX will track them and re-render whenever one of the references changes. As a result, staleness bugs are eliminated. As a programmer, you might forget that changing some data might influence a seemingly unrelated component, but MobX won’t forget.
  • Simpler actions are easier to maintain: Modifying state when using MobX is very straightforward. You can simply write down your intentions. MobX will take care of the rest.

The basic structure of a MobX based application:

The above example makes use of the following properties of MobX that are vital. They are:-

State in MobX = Core-State + Derived-State

Observables 

https://gist.github.com/JOSHIMOH/760b7842a26a12930d8b7e76edffe4e9#file-observable-in-mobx

Actions are functions that decide how to mutate the Observables As a reason of this property, they are also called ‘Mutators’

https://gist.github.com/JOSHIMOH/770593b433d0247351a59ad116e13b41#file-actions

Computed Observables are values which depend upon observables and get triggered when the observable they depend on, changes its state.

https://gist.github.com/JOSHIMOH/df93ad0afefd974fa09a47d5f78e9a3b#file-computed-observable

Observer Widgets are a special type of widget which acts as a listener to the observable properties being rendered on the screen, and simply changes the state and re-renders them whenever any change is observed.

MobX

  • Smaller Application
  • Rapid Prototyping
  • Less Boilerplate Code
  • Observe References
- Single domain class can Encapsulate all of the update logic,
- Reacting to state changes:Real time systems
- Learning Curve is easier,
- Maintainabilty and Scalibility are not a concern
- Automatically track update

MobX Vs Redux: Comparing the opposing Paradigms

Similarities:-
Open Source client side management libraries.
Describe UI as a function of state .
No relation to React.
Work Especially well with React

https://gist.github.com/JOSHIMOH/1ef1df285139d0ce1a2fc1c6a2bc1037#file-plain-in-redux

https://gist.github.com/JOSHIMOH/a4fa2962b292be380b280d685086f7d5#file-redux

Redux:-
Action Required,
Single Store,
Plain-Object,
Immutable,
Normalized State

https://gist.github.com/JOSHIMOH/c806a9519b396fed7a5cc4378996af50#file-observable-in-mobx

MobX:-
Read and Write to State,
Multi- Store,
Observable Data,
Mutable,
Nested State

Making a simple Review App using MobX for Flutter

In this tutorial you will learn how to create a MobX version of the Review app-

Install Dependencies:

Add the following dependencies to your pubspec.yaml file.

dependencies:
mobx: ^latest version
flutter_mobx: ^latest version

Next add the following dev_dependencies:

dev_dependencies:
build_runner: ^latest version
mobx_codegen: ^latest version

In your project folder, run this command to fetch all the packages:

flutter packages get

At this point you possess all the necessary packages to continue further development:-

Implementation of MobX:

Using @observables and @actions annotations we have created reviews.dart

Observable & Actions usage pattern:

@observable
double averageStars = 0;

@action
Future<List<ReviewModel>> _getReviews() async {
final SharedPreferences _preferences =
await SharedPreferences.getInstance();
final List<String> reviewsStringList =
_preferences.getStringList('userReviews') ?? [];
final List<ReviewModel> retrievedReviews = [];

for (String reviewString in reviewsStringList) {
Map<String, dynamic> reviewMap = jsonDecode(reviewString);
ReviewModel review = ReviewModel.fromJson(reviewMap);
retrievedReviews.add(review);
}
return retrievedReviews;
}

Now we need to Run the below command inside our project folder. This generates Auto generated Code file

flutter packages pub run build_runner build

https://gist.github.com/JOSHIMOH/d6749dee5c27c6c4f430863665469e1f#file-review-g-dart

The changes need to be listened also in the UI view. This is done like where Row is wrapped alongwith Observer using builder:-

Observer(
builder: (_) {
return Row(
children: <Widget>[
InfoCard(
infoValue: _reviewsState.numberOfReviews.toString(),
),
],
);
},
),

This will generate a Ratings app with Comment and Rating functionality needed which will get displayed as list and added to average the overall rating on each new review :-

Conclusion:

MobX is framework Independent .

Though as per my suggestion , I would like to suggest you to try it out for your state management in flutter apps , Make Use of Actions if the changes are Event-based to avoid discomfort through handling.

Redux => MobX <=> MobX => Redux Easily doable .

Whatever you choose — It’s not an End game . Choose what makes you a Happy Developer!

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.


ChatBot in Flutter using DialogFlow

0

So, it’s been a while since Flutter is out there and its upsurge these days is phenomenal. The unparalleled performance of the framework is one of the reasons for its fondness among App developers other than the fact that it helps build cross-platform apps.

Today, I am going to tell you how to build a ChatBot in Flutter using the Dialog Flow development suite. So, first let’s see the points that I am going to cover in this article:

  • Brief about Dialogflow
  • Setup and Understand the console
  • Train your Agent
  • Integrate Dialogflow in Flutter App

Let’s move on with the first part where we should know about Dialogflow which is the building block of the ChatBot.

What is Dialogflow?

Dialogflow is a development suite that incorporates Google’s machine learning expertise to build end-to-end,deploy-everywhere interfaces for websites, mobile applications, and IoT devices.

Build natural and rich conversational experiences

Give users new ways to interact with your product by building engaging voice and text-based conversational interfaces, such as voice apps and chatbots, powered by AI. Connect with users on your website, mobile app, the Google Assistant, Amazon Alexa, Facebook Messenger, and other popular platforms and devices.

Advantages of Dialogflow:

  • Powered by Google’s Machine learning
  • Built on Google’s Infrastructure
  • Optimized for Google Assistant

Setup and Understand Dialogflow console:

Moving on, Lets head over to the Dialogflow website by clicking on the https://dialogflow.com/.

  • Click on the Go to Console at the top right corner of the website.
  • Login using the Google account.
  • Create your first agent. Give it a name, set the time zone and your default language for the agent.
  • After clicking on Create , you’ll get the console with all the features that you can implement in your Agent.

Understanding the basic console:

Two things which are the base of an Agent you just created.

  • Intents
  • Entities

7`

Intents:

An intent categorizes an end-user intention for one conversation turn. For each agent, you can define many intents, where your combined intents can handle a complete conversation. When an end-user writes or says something, Dialogflow matches the end-user expression to the best intent in your agent. and based on that intent a response is provided by the agent to the end-user.

Intents are mappings between a user’s queries and actions fulfilled by your software.

There are two default Intents provided by the Dialogflow, namely:

  • Default Fallback Intent: These types of intents are used when the user’s input expression doesn’t match the Intent defined for the Agent.
  • Default Welcome Intent: These types of intents are used when the end-user starts the conversation.

Entities:

Each intent has a parameter and each intent parameter has a type, called the entity type, which dictates exactly how data from an end-user expression is extracted.

Dialogflow provides predefined system entities. For example, there are system entities for matching dates, times, colors, email addresses, and so on. You can also create your own developer entities for matching custom data. For example, you could define a product entity that can match the types of products available for purchase with an Online store agent.

Entities are objects your app or device takes action on.

Train your Agent:

Now, that you have basic knowledge about the Dialogflow console, all that you’ll need to build a basic Agent we can now move forward to train our agent with test cases.

  • Create the Intents based on your requirement
  • Add the training phrases to the Intents
  • Add the response phrases for those training phrases
  • Add the Action and Parameters if required for that Intent
  • Add the Events which will trigger the Intent on the basis of the event occurrence irrespective of the training phrases, if any.
  • Add the context to the Intent.
Training Phrases for the Intent
Response Phrases for the Intent

Once you create an Intent then you can go on creating different intents for different queries. As of now, Dialogflow allows you to create 780 Intents and after that, you need to update the machine learning algorithm manually which you can do by following the steps:

  • Click on the gear icon for your agent.
  • Click the ML Settings tab.
  • Click Train.

Once you have trained your Agent, now you’re ready to integrate your Agent to your Flutter app and before heading over to Flutter, you have to download a JSON file from the console which helps your App to connect to the Agent you’ve just created. To do that follow these steps:

  • Open the Google Cloud Console.
  • Select your Project.
  • From the Navigation drawer click on API's & Services
  • Choose Credentials from the options.
  • From the Credentials window, Select Service account key from the dropdown menu.
  • Next, select the Dialogflow integration option from the Service Account dropdown menu and select JSON from the radio button below that.

That’s it, you’ll have a JSON file downloaded which you’ll need in the next steps.

Integrate Dialogflow in Flutter App

Now, that you have your agent ready and trained you’re all set to integrate it into your Flutter app.

  • First, add the dependency to your pubspec.yaml file. Please make sure to the latest version, check here.
dependencies:   
flutter_dialogflow: ^latest version
  • Create a folder in your project with the name assets and move the JSON file that you’ve downloaded from the Google Cloud Console into it.
  • Open the pubspec.yaml file and add,
flutter:

uses-material-design: true
assets:
- assets/[name_of_your_json_file].json

Now, I won’t show the whole code for the chat app here for that I will attach the link to the GitHub repo so feel free to look into it for the code but here I’ll let you know the part where you setup the code for Dialogflow in the app.

AuthGoogle authGoogle = await AuthGoogle(fileJson: "assets/[your_json_file_name].json").build(); 
Dialogflow dialogFlow =
Dialogflow(authGoogle: authGoogle, language: Language.english);
AIResponse response = await dialogFlow.detectIntent(query);

Note: use the same filename as mentioned in the pubspec.yaml file.

That’s all you’ll need to get your Agent to respond to your questions. The response will have your Agent responses based on your query.

Now, you’re good to go to make your first chatbot in Flutter using Dialogflow. This is the basic example of ChatBot just to give you an idea about how to start it.

Click the GitHub link below to find the source code of the ChatBot. Also, keep in mind not to directly clone the project and run it, it won’t work as I have removed my JSON credentials. All you need to do is replace the JSON file with your JSON obtained from the Google Cloud Console.

Aditsyal/flutter_chatBot
You can’t perform that action at this time. You signed in with another tab or window. You signed out in another tab or…github.com

From Our Parent Company Aeologic

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

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

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 hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, and Twitter for any flutter related queries.

Flutter Animation with Flare

0

The animation is the word that always fills joy in users as well as in developers when it comes to experiencing better user-friendly UI designs. here in Flutter, there are some inbuilt animations provided by flutter but when we need to show something better than this and then we use Flare.

So here I am going to give a little introduction of Flare, Flare is basically used for animations and it helps to get a better UI experience to the user.

for Flare we use 2Dimensions and here you have to create your account if you have not created it before then you start working on it.

In this tool, there are two options Design and Animate, in design first you choose design patterns or images and then you animate all these things, you can also import images like png and SVG according to your choice, in design part, there are many options here you can choose shapes of designs, can rotate, can set scale can also add other features,

while you are designing the basic layout you mainly focus on the position of components and when you want to move your components at different position you have to fill that x and y value with clicking that box beside it and you will observe it is moving with its respective position,

after this we come in animation section here by clicking on each component which you added in a design you can move it according to your choice by giving positions in X-axis and Y-axis when you enter the position of a particular component and click on the box next to it, it automatically moves into the next place.

you can observe it in a video added below where every component is taking place of the component next to it.

This was the basic overview of the tool and we have to move in the next section where we would add it in our App.

How to use flare in Flutter:

As we know that flutter does not have the support of flare so we can implement it by using a plugin.

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec.yaml file.

Dependencies:

flare_flutter: any

after adding this dependency you have to add your flare file in assets

assets:
- assets/flutter_flare_new.flr

How to implement in dart file:

Now after adding dependency and asset, you need to implement it in your code respectively

https://gist.github.com/shivanchalpandey/af45eb9e87812cb47ff6105814d9265e#file-flare_demo-dart

In the above code library of flare has been imported and here a widget FlareFactor has been used to implement the flare. and it is wrapped with Inkwell that makes it interactive when you tap on it, it starts again.

here in the video posted below, you will see how fonts are moving around a button and when you tap anywhere in that circle it starts again, but flutter also provides the functionality by which you can allocate a specific area for tap. It means in different parts of animation you can perform different actions.

So this was the basic introduction of Flare where we did a simple example and you can learn at least how it can be started?

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

Feel free to connect with us:
And read more articles from FlutterDevs.com.

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on 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.


Roadmap To Become A Flutter Developer (Resources for Beginners)

0

Hello Everyone, This article is inlined for those who are keen to start with flutter, A roadmap for beginners to learn gradually from all the necessary resources.

What is Flutter?

Flutter is Google’s UI toolkit for building beautiful, natively compiled applications for mobile, web, and desktop from a single codebase.

Introductory to flutter is in best summarised in below-mentioned videos;

Why Flutter??

We already know there are a lot of frameworks out there that provide the cross-platform functionality then what makes flutter standalone in this rat race?

Fast Development

Flutter’s hot reload helps you quickly and easily experiment, build UIs, add features, and fix bugs faster. Experience sub-second reload times, without losing state, on emulators, simulators, and hardware for iOS and Android. Learn more

Expressive, beautiful UIs

Delight your users with Flutter’s built-in beautiful Material Design and Cupertino (iOS-flavor) widgets, rich motion APIs, smooth natural scrolling, and platform awareness. Browse the widget catalog

Native Performance

Flutter’s widgets incorporate all critical platform differences such as scrolling, navigation, icons and fonts to provide full native performance on both iOS and Android. Examples of apps built with Flutter


Check out what Flutter is capable of

Here are the showcases of flutter apps that developers around the world have built.

Showcase
Apps take flight with Flutter See how customers are using Flutter to make beautiful apps in record timeflutter.dev

Flutter Apps | It’s All Widgets!
An open list of example apps made with Flutter include many open-source samples.itsallwidgets.com

Start Flutter | Free Flutter Themes for Android and iOS
Forever free, open source, and easy to use. Start Flutter is a library of free to download Flutter templates. All…startflutter.com

What to Start With First?

Flutter is fast and easy, If you are familiar with java or any object-oriented language you are good to go but I strongly recommend that you should have the basic knowledge of Dart.

These are some videos that you might find helpful to watch.

For those who are not into watching videos

Tutorials
These tutorials teach you how to use the Dart language, tools, and APIs to build applications. If you want a hands-on…dart.dev

Dart Programming Tutorial
Dart is an open-source general-purpose programming language. It is originally developed by Google and later approved as…www.tutorialspoint.com

Learn Dart In A Week With These Free Resources
In this article, I sum up some of the best resources and tutorials for the Dart programming language as of 2019.hackernoon.com

What make dart so quintessential and why flutter use it?

Why Flutter Uses Dart?

Why Flutter Uses Dart
Many linguists believe that the natural language a person speaks affects how they think. Does the same concept apply to…hackernoon.com

How Does Flutter work under the hood?

Your dart code is directly compiled to native using AOT (Ahead of time ) compilation because iOS doesn’t allow dynamic compilation.

To know more check out these resources below:

Technical overview
What is Flutter?Flutter is an app SDK for building high-performance,high-fidelity apps for iOS, Android, and web([tech…flutter.dev

What’s Revolutionary about Flutter
What is Flutter?hackernoon.com

Flutter is fast and easy to use, now let’s check out how we can install it.

How to Install Flutter?

Here’s the link to the developer docs where you can start to install the flutter in the OS you have.

Install
Select the operating system on which you are installing Flutter:{{site.alert.note}} **Are you on Chrome OS?** If so…flutter.dev

Here are also some articles on Windows, Mac, and Ubuntu that might help.

Have you struck while installing flutter?

If you have any problems with installing flutter and flutter not working, those are some of the issues that have occurred.

Flutter and Dart plugin not installed warnings in flutter doctor · Issue #11940 · flutter/flutter
I’m using IntelliJ CE 2017.2.3 EAP and I get missing plugin warnings in flutter doctor when it seems like everything is…github.com

Android Studio flutter and dart plugins not recognized by flutter doctors, but plugins are…
Hello everybody, I am trying to install flutter on ubuntu, android studio flutter and dart plugins have been…github.com

Having trouble setting flutter path – flutter commands not found
I’ve been trying to set a flutter path so I don’t need to do a temporary path every single time. I’m new to using…stackoverflow.com

Some common issues while installing flutter.

Workaround for common issues
Common issues Flutter developers might run int and recipes how to fix or work arroundgithub.com

Set up an editor for Flutter

Set up an editor
You can build apps with Flutter using any text editor combined with our command-line tools. However, we recommend using…flutter.dev

Create your flutter project

To create flutter project

flutter create <project-name>

or you can use the IDE (Intellij, Android Studio, etc)

Project overview

When you create the flutter app you will see these files and folders, Most of the code is written in dart in lib folder and when In case of the native requirement android and ios are required.

https://dev.to/jay_tillu/flutter-project-structure-1lhe

An article by Jay Tillu explaining about the project structure.

Flutter Project Structure
As always, I’ll be very straight forward and try to keep the article short, simple and very precise. So that in no time…dev.to

Run your first app

Test drive
Do you also want to run your Flutter app on the web? The web version of Flutter is available as early support…flutter.dev

or you can use

To run the your first app

flutter run

and … and .. and

Have got excited when you first app launches (Technically it’s not yours, Code was already there 😜 ). I got excited too 🎉.

When you create your flutter app you will see there is already code for a counter app.

When you run the code, you will see this. This is a simple counter application where you have a FAB(FloatingActionButton) and Text which indicate how many times the FAB has been pressed.

Widgets in flutter

If you see the code you will see StatefulWidget and StatelessWidget. Before we dive into that let’s understand what is a Widget in a flutter.

Introduction to widgets
Flutter widgets are built using a modern framework that takes inspiration from React. The central idea is that you…flutter.dev

Basically, everything you see in your flutter app is a widget.

I find this explanation very accurate about “What is a Widget in Flutter”

What is a Widget in Flutter?
Thanks for contributing an answer to Stack Overflow! Please be sure to answer the question. Provide details and share…stackoverflow.com

There’s also a youtube playlist (Widget of the week )provided by the Flutter team that only talks about Widgets in flutter.

Now

What is a Stateful and Stateless Widget?

In Stateless Widget, all of its properties are immutable which means a StatelessWidget will never rebuild by itself (but can from external events) but a StatefulWidget can.

“Flutter: Stateful vs Stateless Widget” by Souvik Biswas

Flutter: Stateful vs Stateless Widget
In this article, I will show you what is the difference between Stateful and Stateless Widget.medium.com

Let’s create your first flutter app

Google already provides a Codelab where you can learn from scratch that how to build your very first flutter app.

Write Your First Flutter App, part 1
Flutter is Google’s UI toolkit for building beautiful, natively compiled applications for mobile, web, and desktop from…codelabs.developers.google.com

Write Your First Flutter App, part 2
Flutter is Google’s UI toolkit for building beautiful, natively compiled applications for mobile, web, and desktop from…codelabs.developers.google.com

“Build a Flutter app from scratch” by Raman Sah

Flutter Tutorial: How to build an app from scratch
Part 1 of the complete flutter tutorial seriesmedium.com

How to create UI in flutter?

To build the UI in a flutter, you need to get a basic understanding of the layouts and how to work with them.

Layouts in Flutter
What’s the point? Widgets are classes used to build UIs. Widgets are used for both layout and UI elements. Compose…flutter.dev

There’s also a great article on “Flutter layout Cheat Sheet” by Tomek Polański.

Flutter Layout Cheat Sheet
Do you need simple layout samples for Flutter?
I present you my set of Flutter layout code snippets. I will keep it…
medium.com

How to add interactions in your app?

In flutter, you cannot just assign a value and leave it

Example

String value="Hello";

------------------------------
Text(value);

---SOMEWHERE IN THE CODE------

onTap(){

value="How are you?";

}

if you think the text is going to change then you are wrong 🙅‍♂️ , you will have to use setState().

onTap(){

setState({

value="How are you?";

});

}

Adding setState() will rebuild the widget and display the change.

Adding interactivity to your Flutter app
What you’ll learn How to respond to taps. How to create a custom widget. The difference between stateless and stateful…flutter.dev

I would definitely ask you to follow up with the official documentation of flutter regarding the development

Development
flutter.dev

Everything in flutter is a Widget, you can create any custom widget on your own, but there are already defined widget by flutter.

Widget catalog
Create beautiful apps faster with Flutter’s collection of visual, structural, platform, and interactive widgets. In…flutter.dev

JSON Parsing in Flutter

JSON and serialization
It is hard to think of a mobile app that doesn’t need to communicate with a web server or easily store structured data…flutter.dev

Parsing JSON | Flutter
It is really confusing for beginners to understand how to parse JSON data.medium.com

“Parsing complex JSON in Flutter ” by Pooja Bhaumik

Parsing complex JSON in Flutter
Parse different types of simple and complex JSON structures using built-in dart:convert library in Fluttermedium.com

“Working with APIs in Flutter” by Pooja Bhaumik

Working with APIs in Flutter
A beginner’s guide to conquering the world of APIs in Flutter for a better ‘Future’.medium.com

“Handling Network Calls like a Pro in Flutter” by Sahil Kumar

Handling Network Calls like a Pro in Flutter
If you are already in love with Flutter, you must have created many apps as of now. Some of them are maybe small single…medium.com

Use Database persistence in Flutter

SQLite

Persist data with SQLite
If writing an app that needs to persist and query larger amounts of data onthe local device, consider using a database…flutter.dev

Data Persistence with SQLite | Flutter
To work with SQLite database in flutter, you will need sqflite pluginmedium.com

SharedPreferences

shared_preferences | Flutter Package
Wraps NSUserDefaults (on iOS) and SharedPreferences (on Android), providing a persistent store for simple data. Data is…pub.dev

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

Store key-value data on disk
If you have a relatively small collection of key-valuesto save, you can use…flutter.dev

Working with firebase

Add Firebase to your Flutter app | Firebase
Follow this guide to add Firebase products to a Flutter app. Firebase supports frameworks like Flutter on a best-effort…firebase.google.com

Firebase for Flutter
If you’re familiar with object-oriented programming concepts, you should be able to complete this codelab. You don’t…codelabs.developers.google.com

Flutter Firebase by Raja Yogan

Other resources to learn Flutter

Here are some of the resources that other developers and the Flutter team have provided by giving their hearts-in to flutter:

Technical overview
What is Flutter?Flutter is an app SDK for building high-performance,high-fidelity apps for iOS, Android, and web([tech…flutter.dev

“Resources to learn Flutter” by Lara Martín

Resources to learn Flutter
Learn by reading, doing courses and watching videosmedium.com

“Free resources to learn and advance in Flutter” by Katarina Sheremet

Free resources to learn and advance in Flutter
Hey, this is my personal collection of free Flutter resources. If I missed some great resources, please add them in…medium.com

“Flutter Tutorial for Beginners using Dart: Develop Android and iOS mobile app ”by Smartherd

“Flutter Tutorials ” by M T E C H V I R A L

“Flutter ” by Raja Yogan

Flutter Community
Articles and Stories from the Flutter Communitymedium.com

“My Favourite List of Flutter Resources” by Andrea Bizzotto

My Favourite List of Flutter Resources
Flutter is awesome! Big thanks to the Flutter team and all the people in the wider community that keep pushing this…medium.com

Solido/awesome-flutter
Flutter is a mobile app SDK for building high-performance, high-fidelity, apps for iOS and Android, from a single…github.com

londonappbrewery/Flutter-Course-Resources
Learn to Code While Building Apps – The Complete Flutter Development Bootcamp …github.com

A Searchable List of Flutter Resources | FlutterX
A Searchable List of Flutter Resourcesflutterx.com

FlutterDevs
FlutterDevs intent to deliver Flutter apps with high quality. We’ve adopted Design First attitude which helps us…medium.com

Q/A regarding Flutter

FAQ
Flutter is Google’s portable UI toolkit for crafting beautiful, natively compiled applications for mobile, web, and…flutter.dev

“Answering Questions on Flutter App Development” by Deven Joshi

Answering Questions on Flutter App Development
After interacting with a lot of students and developers personally and through my talks and workshops, I realised a lot…medium.com

Flutter Vs. React Native: FAQs for Every Developer
Two technologies that help create mobile apps are earning a lot of traction- for all the good reasons- React Native and…hackernoon.com


This article is only for beginners but I will be coming out with the new article with advanced resources in Flutter.


Thanks for reading this article ❤

If I got something wrong 🙈, Let me know in the comments. I would love to improve.

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.


What’s New in Flutter !

0

Google has created quite a buzz with the roll-out of synchronous updates in Flutter 1.9 & Dart 2.5, it’s developer tool for building Cross-platform apps at Chinese Developer Conference in late ’19 attracting developers around the globe to adapt flutter . Flutter’s newest version allows developers to write for mobile, desktop and web with the single codebase..

Flutter 1.9 & Dart 2.5 has come up with a lot of advancements from their previous version updates to strengthen their app development process and Apparently, The reason why flutter is creating quite a Stir Nowadays.The Major revelation though from all being the Successful Integration of the Flutter Web Support to the main Flutter Repository and Ml integration.

Still Unaware of the Recent Updates , Let’s Go!

Quick Keynotes of Update :

  • Flutter 1.9 Version will allow mobile app development companies to create mobile, web and desktop apps from Single Codebase.
  • Flutter 1.9 include support for iOS 13 and macOS Catalina.
  • Dart Programming Language 2.5 version includes more support for calling C code and superior code completion.
  • Google Updated the Dart Language by integration of ML Autocomplete.

What’s New in Dart 2.5 : Supercharged development?

Flutter web
  • Dart has been updated to version 2.5 ,the Dart SDK brings a technical preview of ML Complete, Google’s take on machine learning-powered automatic code completion. It also includes the ‘Foreign Function Interface’ for calling C code directly from Dart which provides machine learning-powered code completions for the IDE.
  • New language defaults: New projects default to Swift instead of Objective-C and Kotlin instead of Java for iOS and Android projects respectively.
Default Language:
Swift => Objective C
Java => Kotlin
  • Suppport for Flutter Web: Upgrade your Flutter from the master or dev channel, so that you can target the web with the latest experimental version of Flutter .Support for web output with Flutter is still at an alpha phase, but this release represents a major step forward towards enabling Production support for web development with Flutter. It include a flag to tell if an app is running on web (KIsWeb) right now .To view commonly asked questions and answers, see the web FAQ.

Building a web application with Flutter

To add support to an existing flutter project , run the following commands in the terminal of your project package:

Download the Flutter SDK:

Currently, you need either the master or dev channel of the Flutter SDK for web support. If you have the flutter tool installed already , run the following commands to install latest version :

 $ flutter channel dev
$ flutter upgrade

The flutter upgrade command fails when “origin” points to a personal fork. To nulify that enter the following:

cd <inside local copy of the flutter/flutter repo>
git remote get-url origin
ssh://git@github.com/flutter/flutter.git

Use the config command to enable web support:

flutter config --enable-web

Once web is enabled, flutter devices outputs a device named Chrome.

flutter devices
1 connected device:

Chrome • chrome • web-javascript • Google Chrome 76.0.3809.100

After enabling web support, restart the IDE. You Should now see Chrome (web) in the device pulldown to ensure correct installation.

NOTE : Support for web output with Flutter is still at an alpha phase. Not recommended for production yet but you can always Try out!

Also, What’s New in Flutter 1.9 Version?

  • Integrated Web Support with Main Repository of Flutter: With the latest version of Flutter 1.9, developers can have a Unified repository which makes it possible to develop applications for Mobile, Desktop and Web using the Single Codebase.
  • Now when web developers Create a project, the framework would create a web runner using a minimal web/index.html file that bootstraps the web-compiled code and accomplish web development processing.
  • The file would enable using either the Flutter CLI tool or IDE plugins so developers can edit and run flutter applications on the web. It’s built into the dart analyzer availed across dart-enabled editors, including Android Studio, IntelliJ, and VS Code.
For those keen to try Dart ML Complete, Google is recommending using the Flutter dev channel or the Dart dev channel.
  • Support Of New Material Widgets: Flutter 1.9 brings you up a wide range of Features and Material components that can make your web app development process far easier and hassle-free aiming to pixel- perfect User-experience .
  • Toggle Options: It offer a row of buttons and icons and have them as Single-selection or Multi-select options, as well as to require at least one selection also permitting none to be selected.
  • Worldwide Multi-Language Support: Flutter now suppports 24 additional languages including :
flutterpub
  • Selectable text : Making a text selectable is now posssible in this flutter latest version .Use SelectableText.Rich for rich texts .
SelectableText(
'Making Selectable Text',
textAlign: TextAlign.center,
style: TextStyle(fontWeight: FontWeight.bold),
showCursor: true,
cursorwidth: 10
cursorcolor: Colors.green
cursorRadius:Radius.circular(5)
)
  • Structured Error messages : Error message are now made much more developer friendly , credits to flutter team working exponentially diligently to make them more Concise , Understandable and Actionable.
  • Added Support for iOS 13 And macOS Catalina:Google wants to make sure that Flutter is all ready to support the latest version of macOS. Flutter 1.9 added support for new Xcode build systems, enabling 64-bit support throughout the toolchain and simplifies the platform dependencies.

Note: Before upgrading to Catalina, you’ll need to upgrade to the Flutter 1.9.1 stable release the other order works, but you’ll see an error when you do it that way.

  • Flavors introduction: flavors are introduced in flutter also now for all to define some build configuration and switch them if you want : Staging, Development, Release.
  • Flutter build aar: new build command work exactly the same purposely as ‘flutter build apk’ or ‘flutter app bundle ’ but for plugins .
  • Advancement in Toolchain: With the latest release of Flutter 1.9, new projects default to Swift instead of Objective-C and Kotlin instead of java .

For more details on upgrading to Flutter 1.9, including details on how to fix any breaking changes that you might experience as you migrate your code, check out the detailed Flutter 1.9 release notes.

Closing Thoughts

This year has been Quite Eventful for flutter and Dart enthusiasts as this has paved up paths for many to adapt early to this wondrous Framework.

Hopefully, this blog will help you in trying out the Advancements in flutter & Flutter for web early adding a Perfect competitive niche to your business from your Peers.


From Our Parent Company Aeologic

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

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

Feel free to connect with us
And read more articles from FlutterDevs.com

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

Pagination in Flutter with Firebase Firestore

0

Hello Everyone, This article is about how to paginate your data from the Firebase firestore.

What is Pagination?

Pagination, also known as paging, is the process of dividing a document into discrete pages”
When we gradually load the chunks of data and display it.
It’s efficient, quick, and server-friendly to split the results up into multiple data set . if we fetch all the data at one time then things start slowing down the more results which are returned.

What do we want?

We are fetching the data from the firestore in chunks and display it our app.

Fetch data from firestore

We need to fetch all the documents from the movies collection, if we fetch all the data at once, it will be very hard to handle so we need to fetch the data gradually.

Apply cases

We also want the result order by rank.

Lets code 👨‍💻

I am using bloc to handle the data.

https://gist.github.com/ashishrawat2911/551fbc2ec2fa1b35951673481470dae3#file-moviebloc-dart

Set up the app UI

If you see, I have set up a StreamBuilder which will listen to data when sink in stream

In the initState() , I will fetch the first list from the firestore and sink into the stream.

@override
void initState() {
super
.initState();
movieListBloc = MovieListBloc();
movieListBloc.fetchFirstList();
}

let’s define the fetchFirstList() method in the bloc class

https://gist.github.com/ashishrawat2911/3514d4f1065adcaecb8c9bf8223320e3#file-fetchfirstlist-dart

When you run your app, the first 10 documents will be fetched and displayed in the list

Now we will have to paginate the list when the list is scrolled down to the end.

Set up a ScrollController

ScrollController controller = ScrollController();

Now add the listener

@override
void initState() {
super
.initState();
movieListBloc = MovieListBloc();
movieListBloc.fetchFirstList();

controller.addListener(_scrollListener);

}

we will check every time a list reaches at the end and then we fetch the next list.

void _scrollListener() {
if (controller.offset >= controller.position.maxScrollExtent &&
!controller.position.outOfRange) {
print("at the end of list");
movieListBloc.fetchNextMovies();
}
}

Let’s define the fetchNextMovies() in our MovieBloc.

https://gist.github.com/ashishrawat2911/2e5ae1a0dfd1a8b91e40bd3eff96fb7c#file-fetchnextlist-dart

when we fetch the next list, we are appending the documents in the existing list and sink the documents in3 the stream and update the UI using StreamBuilder .

To get the more idea, have a look at more way to paginate your data

Paginate data with query cursors | Firebase
With query cursors in Cloud Firestore, you can split data returned by a query into batches according to the parameters…firebase.google.com

Check out the Github project

ashishrawat2911/Flutter_Firebase_Pagination
Pagination in Flutter with Firebase Firestore This project is a starting point for a Flutter application. A few…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 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.

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

Thank you for reading. 🌸

State Management using Flutter BLoC using Dio and Retrofit

Hello folks!, If you are a Flutter Developer you could have better or bitter experience while developing apps that require you to manage states as well. In flutter, there are various techniques for state management some of them are:

  1. setState()
  2. Inherited widget & Inherited Model
  3. Provider & Scoped Model
  4. Redux
  5. BloC/Rx
  6. MobX
  7. Flutter_BLoc

As a flutter developer, I have experienced that all techniques are best but all have their benefits while flutter_bloc contains important and valuable things from other state management techniques mentioned above.

Why Bloc?

When we are building production quality application state management becomes a critical issue and being a developer we only want to know a few things and these are

  1. How states are changing.
  2. How an application is making interaction that actually helps to make data-driven decisions.
  3. Is the developer able to work with a single code base following the same pattern?
  4. fast and reactive apps.

and it is designed with three core values in mind and these are simplicity, powerfulness, and testability.

Before working with it we need to understand what its inner widgets do and how we manage our data with, Now firstly we have to get the basic knowledge of flutter_bloc.

Basic design patterns are used to make the project well managed, responsible, scalable, and optimized so the flutter_bloc does.

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec.yaml file.

dependencies:

flutter_bloc: ^latest version

Step 2: Import

import ‘package:flutter_bloc/flutter_bloc.dart’;

this is the installation flutter_bloc now let’s move to understand

core concepts of the bloc.

There are various core concepts of the bloc to understand its working,

Events

Events are the inputs of the bloc and it is generally done by making an interaction by the user

Interaction, while designing an app is the basic task and in the upcoming example, we will better know how to fire an event during an interaction.

Generally, we fire an event when we make any interaction when we call onTap but here in the example, we will be making an API call without any button interaction so the event will be fired when we will be instantiating it in main.dart

BlocProvider<UserDetailsBloc>(
builder: (context) => UserDetailsBloc()..add(FetchUserDetailsEvent()), child: UserPage()),

States

States are the output of the bloc, it notifies the UI component of the app and helps it to rebuild itself according to the state.

As we have defined event in the app and it is for fetching data from API, then it will be mapped into the state by bloc and UI will be redrawing itself according to it.

class UserDetailsLoadedState extends UserDetailsState {
UserResponseModel userResponseList;
UserDetailsLoadedState(this.userResponseList);
}

Transition

Transition helps to find out changes from one state to another, It holds the current state and the event and the next state

Basically, it helps to observe when and where states are getting changed It depends on the developer if he/she wants to use it or not.

Now after a small introduction let’s move to the core concept of Flutter Bloc

Bloc

Bloc (Business Logic Component) converts the incoming stream of events into outgoing stream of states

Every bloc converts every event into the state, and it can be accessed by using state property

@override
Stream<UserDetailsState> mapEventToState(UserDetailsEvent event) async* {
if (event is FetchUserDetailsEvent) {
yield UserDetailsLoading();
try {
UserModel userResponseList = await userRepository.userInfo(event.page);
yield UserDetailsSuccessState(userResponseList, event.page);
print(userResponseList);
} catch (e) {
print("error msg ${e.toString()}");
yield UserDetailsFailed(e);
}
}
}

Bloc Builder

Bloc Builder is a flutter widget that requires bloc and builder functions and it manages the widget according to new states

BlocBuilder<BlocA, BlocAState>(
builder: (context, state) {
// return widget here based on BlocA's state
}
)

BlocBuilder also contains few properties like bloc and condition for a specific purpose like when you want to specify a particular bloc and previous bloc. You can find a brief description here.

BlocProvider:

It is used as a dependency injection so that it can provide bloc to its children, there are different types to implement it but it depends on no. of blocs are implemented in any app, for single bloc you use BlocProvider.of<T>(context) but if you are managing your app by multiple blocs the MultiBlocProvider will be used to implement it

MultiBlocProvider(
providers: [
BlocProvider<UserDetailsBloc>(
builder: (context) => UserDetailsBloc()..add(FetchUserDetailsEvent()), child: UserPage()),
],
)

Now let’s implement it, for the sake of simplicity first create a package in the lib and make different classes for the event, state and bloc,

after this first, we make an event in the event class that will be fired when the application will start for fetching data.

abstract class UserDetailsEvent {
const UserDetailsEvent();
}

class FetchUserDetailsEvent extends UserDetailsEvent {
FetchUserDetailsEvent();
}

then we make all possible states which could happen in state class, state class must contain initial state because it is the state before any event has been received.

class UserDetailsState {}

class UserDetailsInitialState extends UserDetailsState {}

class UserDetailsLoading extends UserDetailsState {}

class UserDetailsLoadedState extends UserDetailsState {
UserResponseModel userResponseList;
UserDetailsLoadedState(this.userResponseList);
}

class UserDetailsError extends UserDetailsState {
Error e;
UserDetailsError(this.e);
}

there could be four possible states like

initial state,

loading state: when data is loading,

loaded state: when data is loaded,

error state: if we found any error.

Now let’s move to the bloc, here bloc mapEventToState means which event is fired will be converted in to map, in this code snippet we have called that event which we have fired from event class and all four possible states are used.


class UserDetailsBloc extends Bloc<UserDetailsEvent, UserDetailsState> {
UserRepository userRepository = UserRepository();

@override
UserDetailsState get initialState {
return UserDetailsInitialState();
}

@override
Stream<UserDetailsState> mapEventToState(UserDetailsEvent event) async* {
if (event is FetchUserDetailsEvent) {
yield UserDetailsLoading();
try {
UserModel userResponseList = await userRepository.userInfo(event.page);
yield UserDetailsSuccessState(userResponseList, event.page);
print(userResponseList);
} catch (e) {
print("error msg ${e.toString()}");
yield UserDetailsFailed(e);
}
}
}
}

now let’s understand how we call API using retrofit, for this, we have to add few dependencies retrofit, json_serializable, build_runner, and retrofit_generator

then we define and generate API and for this, you should have at least JSON parameters and then you to define it as mentioned below

here one thing is very important which is @JsonKey(name: “ ”) becuase if JSON response is containing key like “per_page”

then during the parsing, it would give an error, so you need to define it by @JsonKey(name: “per_page”) above the particular key.

then we write the factory method as it is, now it may contain few errors but leave it for now, we will handle it a few steps later

Now we make repository class

import 'dart:async';

import 'package:dio/dio.dart';
import 'package:flutter_demo_bloc_example/retrofit_client/user_details_client.dart';

class UserRepository {
static final UserRepository _singletonUserRepository =
UserRepository._internal();

factory UserRepository() {
return _singletonUserRepository;
}

UserRepository._internal();

Future<dynamic> userInfo(int page) async {
return await UserDetailsClient(Dio()).getUserDetail(page);
}
}

we implement HTTP methods and add parameters required

after this, we import

part 'class_name.g.dart';

in JSON model class(you can see above model class) run a command in the terminal,

flutter pub run build_runner build

here you will observe those errors have gone because all the required methods have been generated automatically and if you make any changes in it then you have to run the next command in the terminal,

flutter pub run build_runner build --delete-conflicting-outputs

the auto-generated files will be refactored.

after we call this API in bloc class and we fetch all the details using state in Our UI

https://gist.github.com/shivanchalpandey/58a32e41fb680e8a5cfb41fdd1f08ee0#file-user_page

this was a small introduction of flutter_bloc.


Thanks for reading this article

If you find something wrong please let me know I will love to improve.


From Our Parent Company Aeologic

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

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

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.