The goal of the go_router package is to simplify the use of the Router in Flutter as specified by the MaterialApp.router constructor. By default, it requires an implementation of the Router Delegate and Route Information Parser classes. These two implementations themselves imply the definition of a custom type to hold the app state that drives the creation of the Navigator. You can read an excellent blog post on these requirements on Medium. This separation of responsibilities allows the Flutter developer to implement several routing and navigation policies at the cost of complexity.
Add Dependency:
Open the terminal in your Flutter project. Then run the following command to install the go_router package in your Flutter Project.$ flutter pub add go_router
or you will add this line to your package’s pubspec. ymal file and run “flutter pub get”
dependencies: go_router: ^6.0.1
Features:
GoRouter has many features:-
> Parsing path and query parameters using a template syntax (for example, “user/:id’).
> Displaying multiple screens for a destination (sub-routes).
> Redirection support — you can re-route the user to a different URL based on application state, for example to a sign-in when the user is not authenticated.
> Backwards compatibility with Navigator API
> Support for both Material and Cupertino apps
Implementation:
Hello Everyone…!!!! Today we learn about routing in the flutter application. To integrate go_router in your app first you have to add MaterialApp.router in the place of the MaterialApp. This constructor accepts many properties like routeInformationParser, routerDelegate, etc.
After that, we create an app_route_config.dart. In this file, we pass all the routes. First, we add the default route which is the home page. In routes, we add a name, path ad pageBuilder. After that, we create a route for the profile page in which we pass the userId and userName. And we also create GoRoute for the about page and contact us page.
And also add errorPageBuilder in which we return MaterialPage and pass ErrorPage as a child. and return the router. This is how we create the routes for navigators.
We also create the route constants for GoRouters. In which we pass all the routes as a string.
At last, we create the UI of the project and in the UI part, we also learn the go_router and how to navigate the UI. In-home. dart we return the scaffold and pass the appbar in which we pass the title. Pass the Column in the body and add the buttons by which we navigate from one screen to another screen.
We can navigate in many ways like push, pushNamed in which we pass the params like userName and UserId or we can directly pass the path of the route which we already defined in the route_config.dart file. This is how we use go_router. I hope you learn many things like how to create paths or routes and how to pass params easily.
In this article, we learn how to implement go_router in Flutter Application. We learn many things like how to create the config file and how to pass params to another screen and many things.
❤ 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.
GitHub Link:
Find the source code of the Navigate With GoRouter In Flutter:
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 fromFlutterDevs.com.
FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn Facebook, GitHub, Twitter, and LinkedIn.
Wewelcome 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.
These days we see several times that as we approach getting signed-in in many applications we need to verify our phone numbers. Although, we can do so in mainly two ways, either by making a phone call or by an OTP — sent as sms to our phone numbers.
So along with that, we have also noticed, that the OTP whichcomes with the sms got filled up automatically in the OTP fields which makes UI more user-friendly. Well, how does that happen? I’m going to answer the question with the help of this article along with my demo project.
In this session, we’d be using the most commonly used package for such purposes, that is sms_autofill.
Working with this package made it comparatively easier and faster to get my expected output. We just need to follow a few steps to make it work properly throughout our project which we’ll discuss later in this article.
To get the OTP sms, I’ve used Firebase Phone Authentication. To achieve that we first need to create a Firebase project in Firebase Console. Once you have created one, make sure that you enable the Phone sign-in method in the Authentication section.
Firebase Phone Authentication:-
Here’s how we do it:-
To know more, you may go to the Apple, Android, or web options according to the project environment in which you build the project. For me it was Android.
Save it as you enable it. It will look like this
Now firstly, we need to send an OTP sms to the entered mobile number.
Here, we’ll pass the phone number (fetched by the TextEditingController) to the phone argument of this function.
We used Future<String> as the return type because we are going to return the verification ID that we get during the process of sending OTP. Further, this verification ID will be needed in the OTP screen.
This is a snippet from the OtpScreen.dart where we are using the verification ID we extracted from CommonUtils.firebasePhoneAuth() method. Along with that, we pass our smsCodereceived. It then matches OTP which was sent and the OTP which is being passed in smsCodealong with the verification ID. If they match, we successfully will be authorized to get through the other page (HomeScreen.dart).
OTP Autofill:-
Now let’s get through the steps to implement otp-auto-filling
Import the latest version of the sms_autofill package in pubspec.yaml file
dependencies: sms_autofill: ^2.2.0
Go to >android >app >build.gradle file and change minSdkVersion from 16 to 19
defaultConfig { // TODO: Specify your own unique Application ID (https://developer.android.com/studio/build/application-id.html). applicationId "com.example.otp_autofill_demo" // You can update the following values to match your application needs. // For more information, see: https://docs.flutter.dev/deployment/android#reviewing-the-build-configuration. minSdkVersion 19 targetSdkVersion flutter.targetSdkVersion versionCode flutterVersionCode.toInteger() versionName flutterVersionName }
Add listner listenForCode() method inside initState() method to listen otp sms as soon as possible.
Use the PinFieldAutoFill() widget as our OTP field. You can apply decoration to it to make it more attracting. I’ve used BoxLooseDecoration() constructor to decorate fields.
Override dispose() method to unregister stream listener. This is a very significant step as the stream should be closed once we’re done using it. Otherwise, we could face memory leakage problem.
As we run the application, this is what we get as our final output.
Conclusion:-
In this article, we’ve learned how to autofill OTP from OTP sms. Moreover, we also got to know about Firebase Phone Authentication and implemented it in the project.
❤ ❤ Thanks for reading this article ❤❤
If I got something wrong? Let me know in the comments. I would love to improve.
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 fromFlutterDevs.com.
FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.
Wewelcome 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.
The Flame Engine aims to provide a complete set of solutions for most of the common problems that games developer might face in the flutter environment.
This article will deliver a quality introduction to the Flutter Flame game engine. You’ll learn how to build a Flutter Flame game, load sprites, and add animations. In the further project, we shall talk about animations made with Flutter Flame.
Flutter is an open-source framework created by Google where we craft various attractive applications for the Android, iOS, web, etc platforms from a single code base. Flutteruses a client-optimized language called Dart that makes faster apps on any platform. It is a much easier approach than traditional methods.
Flutter makes it easy to develop beautiful, interactive, and user-friendly interfaces(UI). Although, Flutter is a framework that is used for both frontend and backend development. But because of its adorable performance in frontend developers mostly use Flutter for Frontend development.
The Flutter team is dedicated to providing the ability to all kinds of developers to build applications in a minimal amount of time and release them effortlessly. For instance, Game developers are now capable of crafting beautiful game apps without taking care of performance issues, load times, and app sizes problems.
Flame:
It is a 2D game engine by which we develop various 2D game applications that run on top of flutter. We get so many useful & amazing features of it such as
Game loop
A component/object system(Flame Component System(FCS))
Collision detection
Images, sprites, sprite sheets, and animations.
Input/gestures handling
General utilities that make development easier.
Installation:-
Initially, you need to install Flame to implement it in your project. For that, we need to add its package with the latest version of it in pubspec.yaml file:
dependencies: flame: ^1.6.0
Code Implementation:-
To attach a Game instance in our Flutter tree, we need to give the charge to the widget called GameWidget. Or in simpler words, we will wrap our game with GameWidget at initials.
Here Game() is the game instance that GameWidget() will render over the screen. “Game” extends the FlameGameclass.
class Game extends FlameGame with HasTappables { @override Future<void>? onLoad() { super.onLoad(); }
FlameGame is a more absolute and opinionated implementation of Game. Extending it makes the developer able to add his game logic or he can keep the logic in the child Component.
FlameGame is based on the Flame Component System (also called FCS). This is the base class mostly recommended to use for most games that are made with Flame.
Component:
Everything we see on top of the screen is all components. For instance, background image, all the characters/objects on the screen, etc.
All components get inherited from the abstract class Component directly or indirectly.
Every Component has a few methods that you can implement optionally while using FlameGame the class. If you are not using FlameGame, you can implement these methods on your game loop if you need.
Few generally used components:
PositionalComponent — This class represents a positioned object over the screen, which could be a floating rectangle or a rotating sprite.
SpriteAnimationComponent — This class is used to represent sprites containing Components that run in a single cyclic animation. I’ll be using it in the further project file for the animation making.
You can download sprite sheets and make your animation UI. Few are here.
Final Output:-
When we run the application, we ought to get the screen’s output like the underneath screen video.
As we click the DialogButton component, we are changing the sprite sheet limits from 0–11(running state) to 12–18(sitting state).
Conclusion:-
In this article, we’ve learned how to work will package flameto encounter animation in our application. We commonly use this package for developing 2D games but it’s indeed a good choice for the making of animations too in our applications.
❤ ❤ Thanks for reading this article ❤❤
If I got something wrong? Let me know in the comments. I would love to improve.
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 fromFlutterDevs.com.
FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a Flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.
Wewelcome 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.
State management is one of the most important aspects of app development. In a large and complex application, keeping track of the state of different widgets and managing the flow of data can quickly become a challenging task. This is where Redux comes in.
Redux is a state management library that is widely used in React and React Native applications. It is also a popular choice for state management in Flutter, a UI toolkit for building natively compiled applications for mobile, web, and desktop.
It provides a centralized store for storing the state of an application, and it follows the unidirectional data flow pattern. In Flutter, Redux can be used to manage the state of an application, making it easier to understand, maintain, and scale.
In this blog, we’ll explore how to integrate Redux into a Flutter application and understand the key concepts of Redux.
Redux is a predictable state management library that is based on the principles of Flux architecture. It is designed to make it easy to manage the state of an application in a centralized and consistent way. The core concepts of Redux are:
State:The state of an application is the data that changes over time, such as user data, API responses, or UI state.
Actions:Actions are events that are dispatched from the view layer to modify the state of the application. Actions have a type and can also have payload data.
Reducer:The reducer is a pure function that takes the current state and an action as inputs and returns the updated state. The reducer defines how the state should be updated based on the action type.
Store:The store is the central place where the state of the application is stored. The store is created by passing the reducer function to it.
By following these core concepts, Redux makes it easy to manage the state of an application consistently and predictably.
Why use Redux in Flutter?
Flutter provides a rich set of built-in widgets and tools for building complex UIs. However, as the size and complexity of a Flutter application grow, it becomes more challenging to manage the state of the application. This is where Redux comes in. By using Redux, you can centralize the state of your application and make it easier to manage.
Some of the benefits of using Redux in Flutter are:
Predictable state management: With Redux, the state of the application is managed in a centralized and consistent way. This makes it easier to understand how the state changes over time and debug any issues that may arise.
Scalability: As the size and complexity of a Flutter application grows, Redux makes it easier to manage the state of the application. By following the core concepts of Redux, you can quickly scale the state management of your application.
Reusable code:By centralizing the state of the application, you can write reusable code that can be shared across different parts of the application.
Easy to test:Because the reducer is a pure function, it is easy to write automated tests. This makes it easier to ensure that the state of the application is being updated correctly
Integrating Redux into a Flutter application:
In Flutter, there are several packages available for implementing Redux, such as flutter_reduxand redux_thunk. To get started with Redux in Flutter, you need to install the flutter_reduxpackage and create a store for your application.
dependencies: flutter_redux: ^7.0.0
The store is created using the createStore() function, which takes the initial state of the store and a reducer as arguments. The initial state is a plain Dart object, and the reducer is a Dart function that takes the store’s current state and action and returns the next state of the store.
Define your application state and action:
class AppState {
int counter;
AppState({this.counter = 0});
}
enum Actions { incrementCounter }
final store = Store<AppState>( appReducer, initialState: AppState(), );
Once the store is created, you can use the StoreProvider widget to provide the store to the rest of the application. The StoreProvider widget takes the store and a child widget as arguments, and it makes the store available to the child widget and all its descendants.
4. Use the StoreProvider widget to provide the store to your application:
In the child widget, you can use the StoreBuilder widget to access the state of the store. The StoreBuilder widget takes a builder function as an argument, which takes the store and returns a widget. The builder function is called whenever the state of the store changes, and it returns the updated UI.
5. Use the StoreBuilder widget to access the state of the store in a widget:
This example demonstrates a basic integration of Redux in a Flutter app. The example shows how to create the store, provide it to the application, access the state of the store, and dispatch actions to update the state.
Note: This is just a basic example to get you started with Redux in Flutter. You can extend and customize it to fit your needs.
Conclusion:
Redux is a powerful state management library that can simplify the state management of a Flutter application. By using Redux, you can keep the state of your application in a single store, and you can manage the flow of data using actions and reducers. With its simple approach, Redux can help you build large and complex Flutter applications with ease.
❤ ❤ Thanks for reading this article ❤❤
If I got something wrong? Let me know in the comments. I would love to improve.
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 fromFlutterDevs.com.
FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter-related queries.
Wewelcome 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.
This blog will explore the Managing State in Flutter with the State Rebuilder Library: A Comprehensive Guide.We perceive how to execute a demo program. We will learn how to implement it in your flutter applications.
State management is one of the key concepts in developing any mobile application. It involves managing the data that affects your application’s UI and the UI itself. In Flutter, there are many ways to handle state management, including using the Scoped Model, Provider, BLoC, and many more. However, there is one lesser-known state management solution in Flutter, called the “State Rebuilder.”
State Rebuilder is a state management library in Flutter that is easy to learn and use, and it provides a simple, yet efficient, way to manage your application’s state. It was created to solve some of the problems associated with traditional state management techniques, such as complexity and code duplication. The library is designed to provide a simple and efficient way to manage the state of your application, making it an excellent choice for small to medium-sized applications.
Why Use State Rebuilder:
One of the key features of State Rebuilder is that it is built on top of streams, making it possible to use the reactive programming paradigm to manage your state. This means that whenever your state changes, the UI of your application will automatically update to reflect the changes, making it easier to develop and maintain your application. In addition, State Rebuilder provides a simple and efficient way to isolate your state management logic from your UI, making it easier to test and maintain your code.
Another advantage of using State Rebuilder is that it provides an easy way to manage a global state, which is a state that affects multiple parts of your application. With State Rebuilder, you can easily manage a global state by creating a single instance of the state management object, and then using it throughout your application. This makes it easy to manage the state of your application, and it eliminates the need for complex state management code.
Integrate State Rebuilder into your Flutter application:
Let’s imagine we want to build a simple counter application in Flutter. The application has a button that increments the counter value when it’s pressed. Here’s how we can use State Rebuilder to manage the state of our counter application:
First, we need to install the states_rebuilder library by adding the following line to our pubspec. yaml file.
dependencies: states_rebuilder: ^6.2.0
Next, we need to create a new instance of the StateRebuilderobject and pass in a function that returns the initial state of our application. In this case, the initial state is simply an integer with a value of 0.
Next, we can create a simple UI that displays the counter value and a button that increments the counter value when it’s pressed. To access the state from within our UI, we use the InheritedRebuilderwidget, and pass in the StateRebuilderobject as a parameter.
Now, whenever the button is pressed, the setStatemethod is called on the StateRebuilderobject. The setStatethe method takes a function as a parameter, which takes the current state as an argument and returns the new state. In this case, we simply increment the current state by 1.
And that’s it! We now have a working counter application that uses State Rebuilder to manage its state. By using State Rebuilder, we have separated our state management logic from our UI, making it easier to test and maintain our code.
Here’s the complete code for our counter application:
With this code, we now have a simple and clean implementation of state management in Flutter using the State Rebuilder library. By using State Rebuilder, we can separate our state management logic from our UI, making it easier to test and maintain our code.
Conclusion:
In conclusion, the State Rebuilder library is a powerful tool for state management in Flutter. It provides a clean and simple approach to managing state in your Flutter applications, allowing you to separate your state management logic from your UI.
With State Rebuilder, you can easily manage complex state interactions and make use of powerful features like state observation and state management via streams. Whether you are a seasoned Flutter developer or just starting the State Rebuilder library is worth considering for your next project.
❤ ❤ Thanks for reading this article ❤❤
If I got something wrong? Let me know in the comments. I would love to improve.
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 fromFlutterDevs.com.
FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter-related queries.
Wewelcome 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.
Hello Everyone!!! Today we learn about Bloc V/S Cubit In Flutter Application. In this article, we cover topics like what is bloc. , what is a cubit and what’s the difference between a bloc and a cubit?
Flutter Bloc is one of the state management in a flutter. We can use it to handle all the states that we want to perform in our Flutter applications.
Bloc is the best and simple way to do state management. We can easily add any type of change to the Flutter application. You can easily learn the concept, no matter what’s your level. You can add this dependency to your project and use it.
Bloc is a design pattern created by Google to help separate business logic from the award layer and authorize a developer to exploit code more efficiently.
A state management library called Bloc was created and maintained by Felix Angelo. It assists developers utensil the Bloc design pattern in their Flutter application. It means that a developer must recognize the state of an app at some time. There should be something on the screen for every interplay with the app to let users know what the incident is incident.
what is a Cubit?
Cubit is a minimal version or a subset of the BLoC design pattern that simplifies the way we manage the state of an application. To do so, it substitutes the use of events (used in Bloc) with functions that rebuild the UI by emitting different states on a stream.
A Cubit is similar to a Bloc but has no notion of events and relies on methods to emit new states. Every Cubit requires an initial state which will be the state of the Cubit before emit has been called. The current state of a Cubit can be accessed via the state-getter.
Bloc VS Cubit:
The only difference is in the syntax of the emitting state. Where Cubit uses emit(event) syntax, State Notifier uses state = event. Bloc on the other hand relies on events instead of functions to get feedback from UI to Cubit. The major difference between Bloc and Cubit is, “Bloc is Event-Driven and Cubit is not Event-Driven”. In Bloc, we can override “onTransition” and check how these events are coming and how these states change. In Cubit, we call functions to send these states, with the help of these functions we can track the state. We use the “onChnaged” function in Cubit.
Add Dependency:
Open the terminal in your Flutter project. Then run the following command to install the flutter_bloc package in your Flutter Project.
$ flutter pub add flutter_bloc
or you will add this line to your package’s pubspec. ymal file and run “flutter pub get”
dependencies: flutter_bloc: ^8.1.2
Import it. Now in your Dart code, you can use:
import 'package:flutter_bloc/flutter_bloc.dart';
Implementation
First, we have to adddependency in pubspec.ymal file for getting all the properties of the bloc by which we can easily use it for state management.
For this demo first, we have to create a logic folder in which we create classes for cubit_logic and bloc_logic. So starts with bloc_logic. For bloc_logic we have to create two classes for counter_bloc and counter_event.
Counter_event.dart:–
abstract class CounterEvent{}
class CounterIncrementEvent extends CounterEvent{}
In this, we create a Counter-event which is used in counter_bloc, and also define the CounterIncrementEvent.
counter_bloc.dart:-
class CounterBloc extends Bloc<CounterEvent, CounterState>{
CounterBloc() : super(CounterInitState());
Stream<CounterState> mapEventToState(CounterEvent event) async*{
switch (event.runtimeType){
case CounterIncrementEvent:
int value = state.value;
value++;
yield CounterResultState(value);
break;
default:
}
}
}
First, we extend the class with Bloc in which we pass the event and state of the bloc. And create a stream with a state in which we pass the event that we want to perform in the application. For the event, we use a switch case.
home.dart:-
In the UI part, first, we have to define counterBloc.
CounterBloc counterBloc;
and pass this counterBloc in initState(). And create a method in which we increment the number.
After that, we create a widget that is wrapped with BlocProvider and pass CounterBloc. and give counterBloc as created in BlocProvider. For that the UI we used BlocBuilder by which we can change the text of the UI. At the onPreesed of the button, we pass the method that we created for increment.
In counter_state.dart we create an abstract class with the name CounterState in which we initialize the value. And also create two more classes for InitState and ResultState.
abstract class CounterState {
late final int value;
@override
CounterState(this.value);
}
class CounterInitState extends CounterState{
CounterInitState(int value) : super(0);
}
class CounterResultState extends CounterState{
CounterResultState(int value) : super(value);
}
counter_cubit.dart:-
In counter. dart class, we create a cubit class that extends to CubitState, in this class, we define the method of incrementing the number. and emit the value of ResultState.
class CounterCubit extends Cubit<CounterState>{
CounterCubit() : super(CounterInitState(0));
void increment() async{
int value = state.value;
value++;
emit(CounterResultState(value));
}
}
home.dart:-
In the UI part, first, we have to define counterBloc.
CounterCubit counterCubit;
and pass this counterBloc in initState(). And create a method in which we increment the number.
After that, we create a widget that is wrapped with BlocProvider and pass CounterCubit. and give counterCubit as created in BlocProvider. For that the UI we used BlocBuilder by which we can change the text of the UI. At the onPreesed of the button, we pass the method which we created for increment.
In this article, we have been through What is Bloc And Cubit in Flutter along with how to implement them in a Flutter. By using we can perform many state management orations.
❤ ❤ 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.
GitHub Link:
Find the source code of the Bloc VS Cubit In Flutter Application:
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 fromFlutterDevs.com.
FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a Flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.
Wewelcome 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.
Hello programmers, If you write UI code then you should know the concepts of the Event Loop architecture of Dart. It ensures that graphics operations and events such as I/O from the disk, finger taps from the user… and so on.
In Computer Science, an Event Loop is a programming construct or design pattern that continually tests and manages events and calls the appropriate routine to handle them. For example, the main function in the program is also the event loop that typically waits for the users to trigger something.
Did You Think ..?
When a program starts executing and dispose of, There are so many events that occur at that time. Can you handle these events yourself, like in which order that events execute or happen, or can you handle all of them with a single thread in that way it never blocks..?
Basic Concept
Dart
Dart is a single-threaded programming language by design because it is a single thread so everywhere we have an Asynchronouscode. Many library functions return future objects and we can register handlers to respond to events such as mouse clicks, file I/O completions & timer expirations…. all kinds of stuff.
So quickly, we can say that Dart handles asynchronous programming by Event Loop.
Event Loop
The event loop handles the execution of multiple chunks of your program over time.
The event loop is what allows multiple operations in a non-blocking way
The multi-threaded system kernel helps handle multiple operations executing in the background
If there is a piece of code that may delay the response, we can tell the event loop to keep it aside until the response is received.
When one of these operations completes, the kernel tells the event loop so that the appropriate callback may be queued to eventually be executed
Simply, An event loop’s job is to take an item from the event queue and handle it, repeating these two steps for as long as the queue has items.
Some Key Points….
Let’s know some points before to know how the Event loop works.
Event Handling Code
Dart uses asynchronous code to handle drawing events, mouse clicks, file I/O completions, timers, and so on. This code is called the Event Handling Code.
Dart’s Event Queues
A Dart app has two queues to run the Event Loop
> Event Queue
The event queue contains all outside events: I/O, mouse events, drawing events, timers, messages between Dart isolates, and so on.
The event queue contains events both from Dart and from elsewhere in the system.
> Microtask Queue
The microtask queue is necessary because the event-handling code sometimes needs to complete a task later, before returning control to the event loop.
Is used to store some very short asynchronous internal actions. All of the actions in the Microtask Queue will be executed before the Event Queue turn
Working on Event Loop Cycle
Let’s know In which order the Event loop works step by step…
Flow Chart Diagram of Working of Event Loop
As the above flow chart shows
When we start App, 1st main() function execute
The Event loop starts its work
Event Loop has two queues: Microtask Queue and Event Queue.
First, it checks the Microtask queue and executes any microtasks, in FIFO order if any exist
Then it dequeues and switches to Event Queue to handle the first item of the event in FIFO order if any exist
Event Loop repeats the cycle: execute all microtasks and then handle the next item on the event queue in FIFO order until both queues are empty and no more events are expected
The event loop closed and App dispose
Code Implementation
Let’s write a sample code to understand the event loop in a practical way
Sample Code:-
Output:-
Did it confuse you?
Let me explain it step by step.
So let’s press the Debug button to run the main() function. The event loop initializes and executes line no. 3 & 4. The next coming event is Future so Event Loop put it somewhere later in a queue and jump to line no. 26.
Here’s something interesting. The next event is the Future.microstack(). It’s a microstack event so Event Loop assigns it to the microstack queue and jumps to the next event. Event loop executed lines no. 29 & 30. So until now, we have A & H printed on the screen.
Next Event Loop checked the microstack queue and executed microtasks in FIFO order so now we get lines no. 26 & 27 output on the screen. Event Loop dequeues the microstack queue and jumps to the event queue where it put Future() in the past.
Now Event loop repeats the same process to handle events. Start execution on line no. 5 . Print lines no. 7, 8, and 11. The next event is Future() so put it somewhere in a queue to print later. Now Event loop gets again a Future.microstack() so it assigns that to the microstack queue and jumps to the next event.
So now we also have B & F printed on the screen. Event Loop checks the microstack queue and executes microtasks in FIFO order until the microtask queue is empty. Event Loop dequeues the microstack queue then checks the Event queue and handles 1st event in the queue until a queue is empty. There are no more events expected so the app dispose
Output:-
Now you have a detailed view of the output. You can see How the Event loop handles the events and in which order it executed the event.
Test Your Understanding
Until that, you explore Event Loop, Keep in mind that
We always can’t depend on Event Loop implementation to manage and handle task orders for the event queue. The implementation might change, and Future’s then() and whenComplete() methods are better alternatives.
Schedule A Task
So when we need to manage task orders or execute some code later then we can use the following APIs provided by the dart: async library: to schedule a task.
The Future class, adds an item to the end of the event queue.
The top-level scheduleMicrotask() function, adds an item to the end of the microtask queue.
Let’s know first that the main() function executes synchronously all existing calls, start to finish
The above flowchart shows in which order the main() function calls the task to execute.
Note:- Use Future().then() or Future().whenComplete() method to the specific task order.
Let’s take another example to test your understanding.
sample code
Output
The output shows, how main() executes the task according to priority and how you schedule tasks according to your requirements.
Conclusion
In this article, we get a details overview of Event Loop, how it manages and deals with the Microtask queue and Event queue, and how to schedule tasks according to our requirements.
When we write asynchronous code, we might need these resources:
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 fromFlutterDevs.com.
FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a Flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.
Wewelcome 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.
Hello Beginners, with this article I am hoping to help you out whenever you may need to represent and visualize or compare some data in graphics form, or sometimes you may still be confused about which type of graphics format you used to represent and visualize data in application development.
Don’t worry in this article, I will give you brief details about it. I will keep it in simple words.
In simple words, As we all know A chart is a representation of data through a diagram, picture, graph, or symbols such as bars, lines, etc to show the relationship between multiple data sets.
It is useful to better understand and predict current and future data.
In Flutter, Real-time work tools for building and project management are largely based on visualization. So a simple chart is not useful for us because it represents static data. We seek a tool that deals with real-time visualization of data which offers us some features like zooming, hovering a marker to get a tooltip choosing a variable to display & more.
Interactive Charts solve our problems. Through this, we deal with complex data easily.
Why is it useful?
Recognize Easily:-
The Human Brain always recognizes graphical data more quickly compared to text data. We also see and deal with data and manage and rearrange data according to conditions in an easy way.
Presenting Relationships more efficiently:-
When we deal with large amounts of data, we may come across events where we need to focus on some very specific metrics. That’s where Interactive charts come in handy. Besides, it allows the users to define timeframes of events by discerning cause-and-effect relationships.
Added values of data storytelling:-
When human written data is aligned in the form of a story and is served as clearly as possible, making it is almost linear when it comes to comparison with the raw data. Graphical data storytelling can convert a complex parabolic function to a linear and readable form. When the data is in interactive chart form, we find ourselves relating with it at every step which causes an imprint in our minds.
When we can zoom in or out the data, and the feature of highlighting the relevant information is added, then it serves as the cherry on the cake. We can filter the data accordingly and change the parameters to make it more clear. It not only makes the presentation better but also helps in increasing the understanding range of users.
Simplification of seemingly chaotic data:-
Dealing with a huge set of data, which may or may not constitute interconnected pieces at first glance, human psychology determines it to be less presentable and even lesser understandable. But with the Interactive chart, we can add at every step, one can connect oneself to the knowledge of the actual writer of the piece, and functions like zooming and filtering, introduce the needed order of events as they are supposed to occur practically. This in addition helps to generate visual insight. Also, including them in financial reports makes the documents more interesting and easier to read and allows users to see trends more clearly.
Keep In Mind:
Do you think, How to format graphs and charts in a better way? whenever you use an Interactive chart then keep some things in mind.
Simplicity:- The first step in the process of formatting graphical or chart data is to keep it as simple as possible. Any use of special effects that might look flashy, must always be avoided.
Ideal visualization- One must have sufficient available data and the capability to present it, that too in such a way that it looks easy to go through. Any visual interactions that are to be used must be first cross-check whether they are of any value to the sole topic of the data.
The purpose of the title must be the purpose of a graph or chart:- The topmost heading must be able to provide the maximum information about what’s inside the data. It helps the readers to get a better insight into whether they need to read that or are looking for someone else. This in turn helps in generating a better review.
Units and measurements must be specified:– The x and the y axis of graphs must always contain the units along with the numerical standardization. One must standardize first that all the values are in billions or millions as per data and this in turn creates a better-looking and lesser complex graph.
Labelling, an important step:- Each part of the graph or chart must have emphasis and must be marked with what it emphasizes. A reader must not have to look all the way around to find what the graph signifies. It should be available right where the graph is.
Finishing touches:- Last but not least, after the concept, is created, and visualization is done, it’s time for the finishing touches. All the data must be re-read and any mistakes should be corrected. If anything improves the core concept of data, it must be implemented. With that, you are ready to go live for the user you are targeting.
Basic Types of Charts:-
Due to the increase in the amount and complexity of data and the need for data analysis to get actionable insights from it, the number of charts provided by different plugins is increasing day by day. Let’s discuss the basic types of charts.
Line Chart
Whenever we have to depict the change of data concerning time, a line chart comes in handy. Each point is separately marked as per time frames and all are connected via a line. Basically, the x-axis depicts the quantity that is changing and the y-axis represents the quantity concerning which the quantity is changing.
It visualizes the numeric, category, date-time, or logarithmic axis of a graph in a chart. We can also represent exponential data through this chart.
Bar chart
A bar chart follows almost the same trend in terms of axial representation. The difference is, that instead of points, bars or rectangles of uniform width are made from the x-axis up to the height proportional to the data to be represented.
The main feature includes that it can also be used to group the data and compare the trends of data change. For example, a bar chart may be used to depict the attendance in each subject or for depicting the developments made by all employees to compare.
Area chart
It also follows the same trend as of line chart. The difference is that the area under the graph is shaded. However, it serves an interestingly important function when many different charts, are merged over one another in different colors.
Making those charts properly translucent, it makes easier to see the changes concerning the time of different quantities.
Column chart
A simple column chart uses vertical bars to display data. Column charts are used to compare values across categories and can be used to show change over some time. In the case of showing change over some time, a column chart can also be displayed as a line chart.
In a column chart, the Y axis is typically used to display a discrete value while the X axis is used to display the category. It’s more or less the same as a bar chart, the difference being it can also be made vertical or horizontal as there is no restriction of the axis.
Pie chart
As the name suggests, it shows a circular statistic graph which mostly serves for representing numerical proportions. The sole purpose being a comparison, it comes in handy when you have to understand the trend in one glance.
The limitation is it only represents the ratio between the quantities and not about the factual quantities unless mentioned. The circular graph is divided into small sectors with varying angles, and the angles are all in proportion to their factual proportions.
Pyramid chart
These charts are used to represent the hierarchical order of different things. The shape is triangular and divided into horizontal sections.
The width of each section determines the ratio between them and the order represents a hierarchy.
Scatter chart
An incredibly powerful form of a chart, it is used when we need to represent the difference and relationship between two variables over time.
Following the same trend of axial distribution, this chart helps to immediately understand a data type, which would rather be impossible in any other type of chart.
Conclusion
The main goal of this article was to demonstrate how to represent or visualize huge or complex data through charts so users easily identify the relationship between data in our flutter app.
Now the challenge is to choose available plugins or libraries for charting in the flutter application. The concept of adding the chart is the same but the data configuration might be a bit different.
I listed some top-rated plugins which easy to implement and load with features.
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 fromFlutterDevs.com.
FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.
Wewelcome 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.
This article will explore the Autofill Username & Password In Flutter. We see how to execute a demo program. We will tell you the best way to enable autofill username & password in your Flutter applications.
The demo video below shows how to create an autofill username & password in Flutter and how an autofill username & password in your Flutter applications. When you enable autofill, at whatever point the user logs in, the application will show a dialog to save the username and password in a browser and store the credentials in a password manager. It will be shown on your device.
Demo Module::
Code Implement:
Create a new dart file called main.dart inside the lib folder.
In the main .dart file. We will create a new class AutofillDemo(). In this class, we will define a Container widget on a body. Inside the widget, we will add the AutofillGroup() method. In this method, we will add the Column widget.
In this widget, we will add two TextFields for Username and Password with autofillHints. Also, we will create an ElevatedButton(). In this button, we will add TextInput.finishAutofillContext(); for password save, and navigate to the home screen and wrap to the onPressed() function. Also, we will add the text “Log In”.
When we run the application, we ought to get the screen’s output like the underneath screen capture.
Outputs
The same dart file called main.dart inside the lib folder.
In the main .dart file. We will create a new class HomeScreen(). In this class, we will define a Column widget on a body. In this widget, we will add an image and ElevatedButton() for logout.
In the article, I have explained the Autofill Username & Password In Flutter; you can modify this code according to your choice. This was a small introduction to the Autofill Username & Password In Flutter User Interaction from my side, and it’s working using Flutter.
I hope this blog will provide you with sufficient information on Trying Autofill Username & Password in your Flutter projects. We will show you what the Introduction is. Make a demo program for working on the Autofill Username & Password in your Flutter applications. So please try it.
❤ ❤ Thanks for reading this article ❤❤
If I need to correct something? Let me know in the comments. I would love to improve.
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 fromFlutterDevs.com.
FlutterDevs team of Flutter developers to build high-quality and functionally rich apps. Hire a Flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.
Wewelcome 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.
In this article, you will learn more about the RawMagnifier in the flutter. For the sake of simplicity, I will not use any package for state management.
Today as we proceed into an increasingly digitalized world, we are making all the specialized types of equipment more and more compact to increase portability. Not more than 2 decades ago, we were using desktops for doing all the text and data-related work. However as a decade passed by, we shifted to laptops and screen sizes went smaller.
Again a decade later, we are now dealing with Androids and tablets which have made our work much more convenient. But, as we proceeded to increase compatibility, screen size reduced drastically. What happened next, is that we find it difficult to read texts from PDFs which are made to appear properly on A4-sized sheets.
Introduction:
For tackling that problem,
Flutter has developed an all-new feature RawMagnifier(). What this deals with is that it makes the text appear bigger only in the part where we want it to increase the size. It works on the same concept as we used a magnifier glass on a small text-sized encyclopedia.
What else does it provide? We can arrange the shape of the magnifier according to our wish with many presets available and even the option to customize it ourselves. It not only helps to zoom in on the selectable text but also to zoom the UI elements of any webpage or PDF. An even more fun part is that the size of this tool is adjustable for the user’s needs.
Before start:
Before starting the tutorial, We will create a page to contain our code.
I take a text file as a sample. Put it in Container to decore it to look fancy.
Container( // adding margin margin: const EdgeInsets.all(10.0), // adding padding padding: const EdgeInsets.symmetric(vertical: 10.0,horizontal: 15), // height should be fixed for vertical scrolling height: MediaQuery.of(context).size.height*0.9, decoration: BoxDecoration( borderRadius: BorderRadius.circular(12), // adding borders around the widget border: Border.all( color: Colors.blueAccent, width: 2.0, ), ), child: Text( data ?? 'Text File Loading', ), )
As you see in the above pic. The text is small and difficult to read here’s flutter comes with a solution.
> RawMagnifier()
To use RawMagnifier() widget, Take a Stack() and put GestureDetector() inside it to set position details on drag. Put the Container in a child of the GestureDetector() because a magnifier will appear on it.
Next, add the Positioned widget to the stack on the top of the GestureDetector() and sets it according to your requirement to save position details on drag. I set it at the top left side position.
Keep in mind that the child of the GestureDetector is the widget that the magnifier will appear on.
So let’s look at our simple demo of RawMagnifier where we drag, it will magnify the content.
You can also customize the RawMagnifier in different ways using its properties. Change magnify scale and size according to requirements.
A decoration: The MagnifierDecoration () property of RawMagnifier could take our customization to the next level with the RawMagnifier class. By using this we can add borders, change the shape and update the opacity of the magnifier.
I used RoundedRectangleBorder() shape in the demo. for example, you can make the magnifier fancy using OvalBorder() object to shape and change the border’s width and color the argument.
>child — An optional widget to position inside the len of the RawMagnifier.
> decoration — MagnifierDecoration This magnifier’s decoration.
> focalPointOffset — The offset of the magnifier from RawMagnifier’s.
> key — Controls how one widget replaces another widget in the tree.
> magnificationScale — How “zoomed in” the magnification subject is in the lens.
> size — The size of the magnifier. This does not include added border, it only includes the size of the magnifier.
Is the Flutter widget worth the hype?
A few notable problems that it may cause to the users is of causing a disturbance in viewing. Some people may find it difficult to read this way as one has to keep moving the screen to read complete lines, from left to right. So it would ultimately be uncomfortable for some. Also, if someone tries to increase the size of the tool to cover the entire horizontal segment to make it convenient to read, it would ultimately not magnify all text of the horizontal segment.
The shape customization feature adds to the fun part when used to present it on screen, however, doesn’t add any real significance. As different viewers may generate different feedback, it’s not likely thing to say whether it would help a large section or not.
Conclusion:
In this article, we have learned about the RawMagnifier(). This magnifying glass is useful for scenarios on mobile devices where the user’s finger may be covering part of the screen where a granular action is being performed, such as navigating a small cursor with a drag gesture, on an image or text.
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 fromFlutterDevs.com.
FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.
Wewelcome 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.