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.
Authentication helps personalize the experience with user-specific information when we develop an application. It’s also a crucial component for privacy and security for the user. Primarily we use Firebase or Rest API for auth in Flutter. In this article, we will use AWS Amplify for authentication.
AWS Amplify
We are always looking for genuine and secure cloud-based authentication systems and what features they offer.
AWS Amplify is a complete solution that lets frontend web and mobile developers easily build, ship, and host full-stack applications on AWS, with the flexibility to leverage the breadth of AWS services as use cases evolve. No cloud expertise is needed.
AWS Amplify looks similar to all the other cloud-based authentication systems. It provides pre-built sign-up, sign-in, and forgot password authentication for user management.
It also provides Multi-Factor Authentication(MFA) to our app. It could handy when we are developing defense or national security-related apps. Amplify also supports login with a social provider such as Facebook, Apple, Google Sign-In, or Login With Amazon and provides fine-grained access control to mobile and web applications.
It gives us two options the Amplify Studio or Amplify CLI to configure an app backend and use the Amplify libraries and UI components to connect our app to our backend.
For this article, to keep things simple, I will use Amplify Studio to configure the app backend and setState() to state management.
To make sure you have installed the proper amplify cli version run the below command:
amplify --version
it’s time to connect to the AWS cloud and for that, we need to initialize the amplify, use the following command to initialize the Amplify:
amplify init
AWS Setup:-
First of all, create an app on Amplify Studio.
click on Launch Studio
Connect your app to this backend environment using the Amplify CLI by running the following command from your project root folder.amplify pull –appId d1chk4cmm2hbfu –envName staging
Inside the Admin UI, Click ‘Authentication’ to get the screen below.
Default ‘Email’ pre-selected.I removed it.
The Authentication screen has 2 panels, the 1st for configuring Sign-in, and the 2nd for configuring sign-up.
First, we focus on Amplify Studio
Auth with Email and Password:
Let’s configure the login mechanism. Select Email from the dropdown menu.
Do the same thing for the signup mechanism.
You can also set up a password policy for sign-up and formatting verification messages. I removed all the password checks and set the character length at 8 to keep things easy.
Click the ‘Deploy’ button and then ‘Confirm Deployment’ to apply signup and login mechanisms.
run the below command again in the terminal to get the latest configuration.amplify pull –appId d1chk4cmm2hbfu –envName staging
Auth with Social Provider(Google):
Let’s configure the login mechanism. Select Any Social provider that you want to use, I selected Google.
Let’s follow some initial steps to set up for web client Id and Secret.
Once the project is created, from the left Navigation menu, select APIs & Services, then select Credentials.
Click CONFIGURE CONSENT SCREEN and Click CREATE
Type in App Information and Developer contact information which are required fields and click SAVE AND CONTINUE three times (OAuth consent screen -> Scopes -> Test Users) to finish setting up the consent screen.
Back to the Credentials tab, Create your OAuth2.0 credentials by choosing OAuth client ID from the Create credentials drop-down list.
Choose Web application as the Application type and name your OAuth Client then Click Create.
Take note of Your client ID and Your Client Secret. You will need them in Amplify Studio and Choose OK.
Select the client you created in the first step and click the edit button.
Copy your user pool domain which displays on Amplify Studio
User pool domain
Paste into Authorized Javascript origins.
Paste your user pool domain with the /oauth2/idpresponse endpoint into Authorized Redirect URIs and click save.
Paste Your client ID and Your Client Secret.
Type ‘myapp://’ in Sign-in & sign-out redirect URLs section. If You want or have another redirect URL for sign-out then click Separate Sign-in and Sign-out URLs and type other URLs for sign-out.
Click the ‘Deploy’ button and then ‘Confirm Deployment’ to apply signup and login mechanisms.
Run the below command again in the terminal to get the latest configuration.
Add the following activity and queries tag to the AndroidManifest.xml file in your app’s android/app/src/main directory, replacing myapp with your redirect URI prefix if necessary.
Now let’s run the app to see if, is everything working fine
Note: If you do a hot restart, you will get the following exception.
PlatformException(AmplifyException, User-Agent was already configured successfully., {cause: null, recoverySuggestion: User-Agent is configured internally during Amplify configuration. This method should not be called externally.}, null)
Don’t worry about it because the library did not detect a hot restart. In future releases, they will fix this bug.
Now come to the UI part of Auth flow. I create four screens.
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 Everyone!!! Today we learn about Assets Generated Dynamically In Flutter In this article, we cover the topics like how to set up the project and dependency and also how we can use dynamically generated assets in the code.
While most of us are developing applications with Flutter, we manually add the assets folder to the pubspec. yaml and make definitions here.
Flutter does not offer such a tool out of the box. Fortunately, there’s FlutterGen, a Flutter code generator for your assets that helps remove all string-based APIs in your app.
An asset is any file bundled and deployed with your application for accessing at runtime. Assets can be in the following forms:
Images
Svg
Fonts
Colors
To load assets in your Flutter app, you have to reference the asset using path strings, which is not safe. The FlutterGen package helps remove all string-based APIs in your app by generating code for all your assets.
We only add icons, images, fonts, and colors in the assets directory like:
Add Dependency:
Add build_runner and FlutterGen to your package’s pubspec.yaml file:
Run flutter packages pub run build_runner build in your root app directory. This command will generate the files for related assets in the lib/res folder. In this case, since three parsers are specified, assets, fonts, and colors, three files are generated for each:
assets.gen.dart — contains generated code for your image, video, animation, and JSON assets
fonts.gen.dart — contains generated code for your font assets
colors.gen.dart — contains generated code for your color assets
Use the generated code:
After the command run the files are generated successfully
You will have to add the file imports to the relevant layout files:
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.
Developing a mobile application is quite a challenging task. There are many frameworks we’re provided with for creating a mobile application. Android provides us with a native framework based on Java language and also, and iOS provides a native framework based on Objective-C / Swift language.
However, to develop an application supporting both OSs, we have to code in two different languages using two different frameworks. To help overcome this convolution, there exist mobile frameworks supporting both OSs. These frameworks range from simple HTML-based hybrid mobile application frameworks (which use HTML for User Interface and JavaScript for application logic) to complex language-specific frameworks (which does the heavy lifting of converting code to native code). Moreover, these frameworks always have many disadvantages also, one of the main drawbacks being their slow performance.
Flutter is a framework that allows developers to build beautiful and responsive user interfaces for multiple platforms using a single codebase. It uses the Dart programming language, which is also developed by Google, to write applications. Flutter provides a layered architecture with customizable widgets, a reactive framework, and a rendering engine, enabling developers to create visually appealing and performant apps.
State Management:-
In Flutter, state management is a crucial aspect of building robust and efficient applications. With the ever-increasing complexity of modern applications, it becomes essential to manage the state of the app in a structured and efficient manner. One popular state management approach in Flutter is using a package called “Binder.” In this article, we will explore Binder and how it can help developers in managing the state of their Flutter applications effectively.
> What is Binder?
The binder is a state management package for Flutter that aims to simplify the process of managing the application state and making it more predictable. It provides a declarative and reactive way of handling state changes, allowing developers to build scalable and maintainable applications.
> Key Concepts of Binder:
State: In Binder, the state represents the current data of your application. It can be as simple as a single value or a complex data structure. The state is immutable, meaning it cannot be modified directly. Instead, you create a new state instance whenever a change occurs.
Binder: A Binder is a class that encapsulates a specific piece of state in your application. It is responsible for managing the state and notifying the widgets that depend on it whenever a change occurs. Binders can be combined to represent the entire state of your application.
Binding: Binding is the process of connecting a widget to a specific piece of state managed by a Binder. When a widget is bound to a state, it automatically rebuilds whenever the state changes, ensuring that the UI stays in sync with the data.
Actions: Actions represent events or user interactions that can cause changes in the state. Binders can define actions that encapsulate the logic for modifying the state in response to these events. Actions can be triggered from various sources, such as user input or network responses.
Important classes for implementing Binder:-
BinderScope() —
A widget that stores a part of the app state.
Any Flutter application must have at least one BinderScope. The more appropriate place to have it is at the root of the widget tree.
And others more descriptively below the Github repository link.
Final Output:-
Conclusion:-
State management is a critical aspect of building Flutter applications, and Binder offers a powerful solution to simplify this process. By leveraging the reactive and declarative nature of Binder, you can efficiently manage state updates and keep your UI components in sync with the underlying data. With its simplicity, scoped state management, and integration capabilities, Binder is a valuable tool to consider for your next Flutter 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 you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.
Machine learning has a rich history, dating back to the previous century, and it has become an integral part of our daily lives. It is so pervasive that we often encounter it without even realizing it. Take smartphones, for example. They are called “smart” because they continuously learn from our interactions and adapt to our preferences. They gather information about us and use it to provide personalized experiences. This extends beyond smartphones and permeates various technologies. Machine learning algorithms are constantly evolving, just like humans, as they analyze data and uncover patterns to make predictions and improve decision-making. Its reach is extensive, impacting numerous areas of technology and enhancing our lives in remarkable ways.
Machine Learning is a branch of artificial intelligence (AI) that focuses on developing algorithms and models that enable computers to learn from and make predictions or decisions based on data, without being explicitly programmed. It involves the development of mathematical and statistical models that can analyze large amounts of data, identify patterns, and make informed predictions or take action.
In machine learning, computers are trained using example data, called the training set, to learn patterns and relationships within the data. The models are then used to make predictions or decisions on new, unseen data.
Machine learning has various applications, including but not limited to image and speech recognition, natural language processing, recommendation systems, fraud detection, autonomous vehicles, and predictive analytics. It plays a crucial role in enabling computers to learn and improve from experience, leading to intelligent and data-driven decision-making.
Machine learning is widely used in various aspects of our daily lives. Here are some common examples:
— Virtual Assistants: Virtual assistants like Siri, Google Assistant, and Alexa utilize machine learning algorithms to understand and respond to voice commands, provide recommendations, and perform tasks based on user interactions.
— Recommendation Systems: Platforms like Netflix, Amazon, and Spotify employ machine learning to analyze user preferences and behavior, suggesting personalized movie or TV show recommendations, product recommendations, and customized playlists.
— Fraud Detection: Financial institutions use machine learning to detect and prevent fraudulent activities by analyzing patterns and anomalies in transactions, identifying suspicious behavior, and alerting users or taking necessary actions.
— Image and Speech Recognition: Machine learning powers facial recognition systems used in unlocking smartphones or tagging people in photos. It also enables speech recognition technologies like transcription services, voice assistants, and voice-controlled devices.
— Natural Language Processing (NLP): NLP techniques, a branch of machine learning, are used in language translation services, sentiment analysis, chatbots, and voice-enabled interfaces, making communication more efficient and intuitive.
— Healthcare: Machine learning algorithms are utilized in medical imaging analysis, disease diagnosis, personalized medicine, and drug discovery, aiding in early detection, treatment planning, and research advancements.
— Social Media and Advertising: Social media platforms employ machine learning algorithms to personalize content feeds, target advertisements based on user preferences and behavior, and detect spam or abusive content.
— Autonomous Vehicles: Machine learning plays a crucial role in autonomous vehicles, enabling object detection, collision avoidance, lane detection, and decision-making based on real-time data from sensors.
Flutter with Machine Learning:-
Flutter with machine learning refers to the combination of the Flutter framework and machine learning techniques in app development. Flutter is an open-source UI framework developed by Google for building cross-platform applications. It allows developers to create beautiful and performant apps for multiple platforms using a single codebase.
When combined with machine learning, Flutter enables the integration of AI capabilities into mobile apps. Developers can leverage machine learning libraries, APIs, and models to incorporate features like image recognition, natural language processing, sentiment analysis, recommendation systems, and more.
By utilizing Flutter with machine learning, developers can create powerful and intelligent mobile applications that can understand, analyze, and make predictions based on user data or real-time inputs. This combination opens up possibilities for developing smart and personalized apps that can provide advanced functionality, improve user experiences, and automate tasks using machine learning algorithms and models.
Installation:-
There are so many packages available for implementing machine learning in Flutter projects. Today we are going to use “tflite”.
Now let’s get through the steps to Import tfilte in our project.
Import the latest version of the tflite package in pubspec.yaml file
dependencies: tflite: ^1.1.2
Go to >android >app >build.gradle file, add aaptOptions block and change minSdkVersion to 19
aaptOptions {
noCompress 'tflite'
noCompress 'lite'
}
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 internet permission to android>app>src>main>AndroidManifest.xml
A model refers to a pre-trained machine learning model that is used within a Flutter application to perform tasks such as image recognition, natural language processing, or data analysis.
The model file contains the learned parameters and structure of the trained model. It is usually saved with a specific file extension, such as .tflite for TensorFlow Lite models. This file is then loaded and used within the Flutter app to perform predictions or inferences on new data.
There are so many ways to create your custom TensorFlow Lite model. I preferred Teachable Machine. It is a web-based tool, by Google that makes it fast and easy to create machine learning models without any expertise or coding accessible to everyone.
— In the demo project below, I’ll showcase the implementation of an image recognition feature using machine learning. So I selected the “Image Project” option.
— Provide samples of all the scenarios in which you want things/yourselves to be recognized, and finally train your model. Afterward, download your TensorFlow Lite model with floating point conversion type.
— Extract your files and paste them into assets/ folders.
— Don’t forget to add an assets section in your pubspec.yaml file, like this
Now, let’s dive into the code implementation to determine if a person is wearing glasses. Below, you’ll find the essential code snippets to achieve this functionality.
class MyApp extends StatefulWidget {
const MyApp({super.key});
@override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
String backgroundImage = "assets/images/background.jpg";
ImagePicker imagePicker = ImagePicker();
File? _image;
double? _imageWidth;
double? _imageHeight;
var _recognitions;
//needs to be called at very first
loadModel() async {
Tflite.close();
try {
String? res = await Tflite.loadModel(
model: "assets/model_unquant.tflite",
labels: "assets/labels.txt",
numThreads: 2,
isAsset: true,
useGpuDelegate: false);
} on PlatformException {
debugPrint("Failed to load the model");
}
}
// run prediction using TFLite on given image
Future predict(File image) async {
var recognitions = await Tflite.runModelOnImage(
path: image.path,
imageMean: 0.0,
imageStd: 255.0,
numResults: 2,
threshold: 0.6,
asynch: true // defaults to true
);
debugPrint("Recognitions:--$recognitions");
setState(() {
_recognitions = recognitions;
});
}
// send image to predict method selected from gallery or camera
sendImage(File image) async {
// if(image == null) return;
await predict(image);
// get the width and height of selected image
FileImage(image)
.resolve(const ImageConfiguration())
.addListener((ImageStreamListener((ImageInfo info, bool _) {
setState(() {
_imageWidth = info.image.width.toDouble();
_imageHeight = info.image.height.toDouble();
_image = image;
});
})));
}
// select image from gallery
selectFromGallery() async {
var image = await imagePicker.pickImage(source: ImageSource.gallery);
if (image == null) return;
setState(() {});
File fileImage = await CommonUtils.convertXFileToFile(image);
sendImage(fileImage);
}
// select image from camera
selectFromCamera() async {
var image = await imagePicker.pickImage(source: ImageSource.camera);
if (image == null) return;
setState(() {});
File fileImage = await CommonUtils.convertXFileToFile(image);
sendImage(fileImage);
}
@override
void initState() {
super.initState();
loadModel().then((val) {
setState(() {});
});
}
Widget printValue(rcg) {
//Print data in your screen accordingly.
}
@override
Widget build(BuildContext context) {
Size size = MediaQuery
.of(context)
.size;
double finalW;
double finalH;
if (_imageWidth == null && _imageHeight == null) {
finalW = size.width;
finalH = size.height;
} else {
double ratioW = size.width / _imageWidth!;
double ratioH = size.height / _imageHeight!;
finalW = _imageWidth! * ratioW * .85;
finalH = _imageHeight! * ratioH * .50;
}
return Scaffold(...);
}
The complete code for this implementation can be found on the GitHub link below. Refer master branch.
Final Output:-
Conclusion:-
In this article, we explored the exciting intersection of Flutter and machine learning, empowering you to create projects that leverage the power of artificial intelligence. I hope you found this journey insightful and enjoyable. Now, armed with the knowledge of Flutter and machine learning, unleash your creativity and embark on your unique ventures in AI.
❤ ❤ 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.