Google search engine
Home Blog Page 70

Managing State in Flutter with the State Rebuilder Library: A Comprehensive Guide

0

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.


Table of Contents:

What is the State rebuilder in Flutter

Why Use State Rebuilder

Integrating State Rebuilder into your Flutter application

Conclusion


What is the State rebuilder in Flutter:

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 StateRebuilder object 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.

final _rebuilder = StateRebuilder<int>(
initialValue: 0,
builder: (state) => Text(state.toString()),
);

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 InheritedRebuilder widget, and pass in the StateRebuilder object as a parameter.

class MyHomePage extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: InheritedRebuilder(
rebuilder: _rebuilder,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
_rebuilder.state.toString(),
style: Theme.of(context).textTheme.headline4,
),
],
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => _rebuilder.setState((state) => state + 1),
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}

Now, whenever the button is pressed, the setState method is called on the StateRebuilder object. The setState the 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:

import 'package:flutter/material.dart';
import 'package:state_rebuilder/state_rebuilder.dart';

void main() => runApp(MyApp());

class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter State Rebuilder Example',
theme: ThemeData(
primarySwatch: Colors.blue,
),
home: MyHomePage(),
);
}
}

class MyHomePage extends StatelessWidget {
final _rebuilder = StateRebuilder<int>(
initialValue: 0,
builder: (state) => Text(state.toString()),
);

@override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: InheritedRebuilder(
rebuilder: _rebuilder,
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text(
'You have pushed the button this many times:',
),
Text(
_rebuilder.state.toString(),
style: Theme.of(context).textTheme.headline4,
),
],
),
),
),
floatingActionButton: FloatingActionButton(
onPressed: () => _rebuilder.setState((state) => state + 1),
tooltip: 'Increment',
child: Icon(Icons.add),
),
);
}
}

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.

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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

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


Bloc V/S Cubit In Flutter Application

0

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?

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table Of Contents

What is Bloc?

What is Cubit?

Bloc VS Cubit

Add Dependency

Implementation

Conclusion

GitHub Link


What is Bloc?

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 add dependency in pubspec.ymal file for getting all the properties of the bloc by which we can easily use it for state management.

dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
flutter_bloc: ^8.1.2

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.

void _incrementCounter(){
counterBloc.add(CounterIncrementEvent()); ///bloc_state
}

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.

Widget blocStateScreen(BuildContext context) {
return BlocProvider<CounterBloc>(
create: (context)=> counterBloc,
child: Scaffold(
appBar: AppBar(
centerTitle: true,
title: const Text(AppStrings.appbarText),
),
body: Center(
child: Padding(
padding: const EdgeInsets.only(top: 200),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const Text(AppStrings.blocCounter),
BlocBuilder<CounterBloc, CounterState>(
builder: (context, state)
=> Text('${state.value}')),
OutlinedButton(
style: ButtonStyle(
side: MaterialStateProperty.all(const BorderSide(
color: Colors.black,
width: 1.5,))),
onPressed: () {
_incrementCounter();
},
child: const Text('+', style: TextStyle(fontSize: 25),))
],
),
),
),
),
);
}

Output of Bloc


counter_state:-

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.

void _incrementCounter(){
counterCubit.increment();
}

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.

Widget cubitStateScreen(BuildContext context) {
return BlocProvider<CounterCubit>(
create: (context)=> counterCubit,
child: Scaffold(
appBar: AppBar(
centerTitle: true,
title: const Text(AppStrings.appbarText),
),
body: Center(
child: Padding(
padding: const EdgeInsets.only(top: 200),
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const Text(AppStrings.cubitCounter),
BlocBuilder<CounterCubit, CounterState>(
builder: (context, state)
=> Text('${state.value}')),
OutlinedButton(
style: ButtonStyle(
side: MaterialStateProperty.all(const BorderSide(
color: Colors.black,
width: 1.5,))),
onPressed: () {
_incrementCounter();
},
child: const Text('+', style: TextStyle(fontSize: 25),))
],
),
),
),
),
);
}

Output of Cubit


Conclusion:

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:

GitHub – flutter-devs/bloc-cubit_demo
You can’t perform that action at this time. You signed in with another tab or window. You signed out in another tab or…github.com


From Our Parent Company Aeologic

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

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

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

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

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


Event Loop In Dart

0

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.

If you’re looking for the best flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table of Contents….

Introduction

Did You Think ..?

Basic Concept

Some Key Points

Working on Event Loop Cycle

Code Implementation

Test Your Understanding

Conclusion

Reference


Introduction

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 Asynchronous code. 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.

  1. The Future class, adds an item to the end of the event queue.
  2. 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:

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

Reference:

The Event Loop and Dart
Asynchronous code is everywhere in Dart. Many library functions return Future objects, and you can register handlers to…dart.cn


From Our Parent Company Aeologic

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

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

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

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

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


https://flutterdevs.com/hire-developers

Interactive Charts In Flutter

0

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.

If you’re looking for the best flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table of Content

Introduction

Why is it useful?

Keep In Mind

Basic Types Of Chart

Conclusion


Introduction:

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.

fl_chart | Flutter Package
This is a temporary and very important message: 💥 FL Chart is a highly customizable Flutter chart library that…pub.dev

syncfusion_flutter_charts | Flutter Package
The Flutter Charts package is a data visualization library written natively in Dart for creating beautiful, animated… pubs.dev

syncfusion_flutter_gauges | Flutter Package
The Flutter Gauges library includes the data visualization widgets Linear Gauge and Radial Gauge (a.k.a. circular…pub.dev

graphic | Flutter Package
The graphic is a grammar of data visualization and Flutter charting library. A Grammar of Graphics: Graphic derives from…pub.dev

flutter_echarts | Flutter Package
A Flutter widget to use Apache ECharts reactively. Note: Since it is based on webview, this library has some…pub.dev

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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

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

Autofill Username & Password In Flutter

0

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.

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table Of Contents::

Introduction

Code Implement

Code File

Conclusion



Introduction:

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.

Container(
padding: const EdgeInsets.all(30),
child: AutofillGroup(
child: Center(
child: Column(
children: [
const SizedBox(
height: 30,
),
Image.asset(
"assets/images/logo.png",
height: 100,
),
const SizedBox(
height: 30,
),
const TextField(
autofillHints: [AutofillHints.username],
decoration: InputDecoration(hintText: "Username"),
),
const SizedBox(
height: 10,
),
const TextField(
obscureText: true,
autofillHints: [AutofillHints.password],
decoration: InputDecoration(hintText: "Password"),
),
const SizedBox(
height: 30,
),
ElevatedButton(
onPressed: () {
TextInput.finishAutofillContext();
Navigator.pushReplacement(context,
MaterialPageRoute(builder: (context) {
return const HomeScreen();
}));
},
child: const Text("Log In"))
],
),
)),
)

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.

Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(
"assets/images/logo.png",
height: 100,
),
const SizedBox(
height: 100,
),
ElevatedButton(
onPressed: () {
Navigator.pushReplacement(context,
MaterialPageRoute(builder: (context) {
return const AutofillDemo();
}));
},
child: const Text("Log Out"))
],
),

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Code File:

import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_autofill_demo/splash_screen.dart';

void main() {
runApp(const MyApp());
}
class MyApp extends StatelessWidget {
const MyApp({super.key});

@override
Widget build(BuildContext context) {
return const MaterialApp(
debugShowCheckedModeBanner: false,
home: Splash(),
);
}
}

class AutofillDemo extends StatefulWidget {
const AutofillDemo({super.key});

@override
_AutofillDemoState createState() => _AutofillDemoState();
}

class _AutofillDemoState extends State<AutofillDemo> {
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: const Text(
"Flutter Autofill Username & Password Demo",
style: TextStyle(fontSize: 18),
),
backgroundColor: Colors.cyan,
),
body: Container(
padding: const EdgeInsets.all(30),
child: AutofillGroup(
child: Center(
child: Column(
children: [
const SizedBox(
height: 30,
),
Image.asset(
"assets/images/logo.png",
height: 100,
),
const SizedBox(
height: 30,
),
const TextField(
autofillHints: [AutofillHints.username],
decoration: InputDecoration(hintText: "Username"),
),
const SizedBox(
height: 10,
),
const TextField(
obscureText: true,
autofillHints: [AutofillHints.password],
decoration: InputDecoration(hintText: "Password"),
),
const SizedBox(
height: 30,
),
ElevatedButton(
onPressed: () {
TextInput.finishAutofillContext();
Navigator.pushReplacement(context,
MaterialPageRoute(builder: (context) {
return const HomeScreen();
}));
},
child: const Text("Log In"))
],
),
)),
),
);
}
}

class HomeScreen extends StatelessWidget {
const HomeScreen({super.key});

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: const Text("Home Page"),
backgroundColor: Colors.cyan,
),
body: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(
"assets/images/logo.png",
height: 100,
),
const SizedBox(
height: 100,
),
ElevatedButton(
onPressed: () {
Navigator.pushReplacement(context,
MaterialPageRoute(builder: (context) {
return const AutofillDemo();
}));
},
child: const Text("Log Out"))
],
),
),
);
}
}

Conclusion:

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.

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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

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


RawMagnifier in Flutter

0

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.

If you’re looking for the best flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table of Content

Do You Think?

Introduction

Before We Start

Constructor

Properties

Is the Flutter widget worth the hype?

Conclusion

Github

Reference


Do You Think?

Let’s first discuss the widget.

Why do we need it?

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.

import 'package:flutter/material.dart';
class MagnifierDemo extends StatefulWidget {
const MagnifierDemo({Key? key}) : super(key: key);

@override
State<MagnifierDemo> createState() => _MagnifierDemoState();
}

class _MagnifierDemoState extends State<MagnifierDemo> {

@override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: const Text("Raw Magnifier"),
centerTitle: true,
),
body: const Center(
),
),
);
}
}

It will show an empty page and I will put the code in the child.

First I created a directory in the project module and named its assets. Add a sample.txt file to the assets folder.

Add a text file

We can also use a pdf file or image file—any data which you want to magnify for the user.

Also, edit pubspec.yaml file to give a path for sample.txt

Giving path to load assets

Write a method loadData() to load the txt file and I call this method in intiState(). String? data;

void loadData() async {
final loadedData = await rootBundle.loadString('assets/text/sample.txt');
setState(() {
data = loadedData;
});
}

@override
void initState() {
super.initState();
loadData();
}

To know more about initState().

initState method – State class – widgets library – Dart API
Called when this object is inserted into the tree. The framework will call this method exactly once for each State…api.flutter.dev

Let’s come to the design part.

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.

Stack(
children: <Widget>[
GestureDetector(
onPanUpdate: (DragUpdateDetails details) =>
setState(
() {
dragGesturePosition = details.localPosition;
},
),
child: 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',
),
)

),
Positioned(
left: dragGesturePosition.dx,
top: dragGesturePosition.dy,
child: const RawMagnifier(
decoration: MagnifierDecoration(
shape: RoundedRectangleBorder(
side: BorderSide(color: Colors.black, width: 3),
),
),
size: Size(180, 70),
magnificationScale: 1.3,
),
)

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.

RawMagnifier(
decoration: MagnifierDecoration(
shape: OvalBorder(
side: BorderSide(color: Colors.black, width: 3),
),
),
size: Size(Github180, 70),
magnificationScale: 1.3,
),

Constructor:

Let’s explore the constructor of the RawMagnifier.

const RawMagnifier({
super.key,
this.child,
this.decoration = const MagnifierDecoration(),
this.focalPointOffset = Offset.zero,
this.magnificationScale = 1,
required this.size,
})

Properties:

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

Final Output Video

Github:

GitHub – RitutoshAeologic/magnifier_demo
A new Flutter project. This project is a starting point for a Flutter application. A few resources to get you started…github.com


❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


Reference :

RawMagnifier class – widgets library – Dart API
A common base class for magnifiers. This sample demonstrates what a magnifier is, and how it can be used. To create a…api. flutter.dev


From Our Parent Company Aeologic

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

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

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

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

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


Implementing Auth using AWS Amplify in Flutter

0

In this article, we are going to use AWS Amplify for Authentication. We will auth via email and use provider Goggle for Social Auth for a demo app.

If you’re looking for the best flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table of Content

Authentication

AWS Amplify

Pre-requisites

AWS Setup

Auth with Email and Password

Auth with Social Provider(Google)

Android Platform Setup

Demo Setup

Demo Video

Conclusion

Github

Reference


Authentication

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.

We auth the app by two-way

  • Email and Password
  • Social Provider(Google)

Pre-requisites

Before starting make sure of these steps.

Read the below link for more details

https://docs.amplify.aws/lib/project-setup/prereq/q/platform/flutter/

Note:

  • Import Amplify packages into your project inside the pubspec.yaml file:
amplify_core: '<1.0.0'
amplify_auth_cognito: '<1.0.0'
  • 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.

  • Go to Google developer console.
  • Click NEW PROJECT
  • Type in a project name and click CREATE
  • 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.
amplify pull --appId d1chk4cmm2hbfu --envName staging

Android Platform Setup:

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.

<queries>
<intent>
<action android:name=
"android.support.customtabs.action.CustomTabsService" />
</intent>
</queries>
<application>
...
<activity
android:name="com.amplifyframework.auth.cognito.activities.HostedUIRedirectActivity"
android:exported="true">
<intent-filter>
<action android:name="android.intent.action.VIEW" />
<category android:name="android.intent.category.DEFAULT" />
<category android:name="android.intent.category.BROWSABLE" />
<data android:scheme="myapp" />
</intent-filter>
</activity>
...
</application>

For more details use the below link.

https://docs.amplify.aws/lib/auth/social/q/platform/flutter/


Demo Setup:

Before coming to the UI part of the App. First, implement AWS API calls for the sign-in and sign-up.

I create AWSAuthRepo and call AWS Api.

class AWSAuthRepo {
Future<bool> getCurrentUser({required bool signedIn}) async {
final user = await Amplify.Auth.getCurrentUser();
if(user != null ){
signedIn = true;
}
else {
signedIn = false;
}
print('$user');
return signedIn;
}

Future<void> signUp(String email, String password, context) async{
try {
final CognitoSignUpOptions options = CognitoSignUpOptions();
await Amplify.Auth.signUp(username: email, password: password, options: options);
} on AmplifyException catch(e){
CommonUtils.showError(context, e.toString());
}
}

Future<void> signUpConfirmation(String email, String confirmationCode ) async{
try {
await Amplify.Auth.confirmSignUp(username: email, confirmationCode: confirmationCode);
} on Exception{
rethrow;
}
}

Future<void> signIn(String email, String password, context) async {
try {
await Amplify.Auth.signIn(username: email, password: password,);
await Amplify.Auth.getCurrentUser();
}
on AmplifyException catch(e){
CommonUtils.showError(context, e.toString());
}
}

Future<void> signOut() async {
try{
await Amplify.Auth.signOut();
}
on Exception{
rethrow;
}
}

Future<void> signInWithWebUI() async{
try {
final result =
await Amplify.Auth.signInWithWebUI(provider: AuthProvider.google);
print('Result: $result');
} on AmplifyException catch (e){
print(e.message);
}
}
}

To initialize amplify, call the following method inside the initState() method in the main file.

@override
void initState() {
super.initState();
_configureAmplify();
}

void _configureAmplify() async {
try {
await Amplify.addPlugin(AmplifyAuthCognito());
await Amplify.configure(amplifyconfig);
setState(() =>
_isAmplifyConfigured = true
);
print('Successfully configured');
} on Exception catch (e) {
print('Error configuring Amplify: $e');
}
}

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.

Sign-In Screen

class LogInPage extends StatefulWidget {
const LogInPage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<LogInPage> createState() => _LogInPageState();
}

class _LogInPageState extends State<LogInPage> {
AWSAuthRepo auth = AWSAuthRepo();
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
final TextEditingController emailTextController = TextEditingController();
final TextEditingController passwordTextController = TextEditingController();
bool validate = false;
bool configuredAmplify = false;

@override
void initState() {
// TODO: implement initState
super.initState();
}
void clearText(){
emailTextController.clear();
passwordTextController.clear();
}
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: (){
FocusScope.of(context).unfocus();
},
child: Scaffold(
backgroundColor: AppColors.lightBlueGrey,
appBar: AppBar(
automaticallyImplyLeading: false,
centerTitle: true,
title: Text(widget.title),
backgroundColor: AppColors.mediumTeal,
),
body:
SingleChildScrollView(
child: Form(
key: _formKey,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 32.0),
child: Column(
children: [
const SizedBox(height: 20,),
Text(AppString.loginPageText,
style: AppTextStyle.text1),
const SizedBox(height: 40,),
SizedBox(
width: MediaQuery.of(context).size.width,
height: 60,
child:
GrayGetTextField(
hint: 'User Email',
obscure: false,
controller: emailTextController,
isVisible: false,
onValidate: CommonUtils.isValidateEmail,
valueDidChange: (String? value) {
if(validate){
_formKey.currentState!.validate();}
}, inputType: TextInputType.emailAddress,)
),
const SizedBox(height: 20,),
SizedBox(
width: MediaQuery.of(context).size.width,
height: 60,
child: GrayGetTextField(
hint: 'Password',
obscure: true,
controller: passwordTextController,
isVisible: true,
onValidate: CommonUtils.isPasswordValid,
valueDidChange: (String? value) { if(validate){
_formKey.currentState!.validate();
} }, inputType: TextInputType.text,)
),
const SizedBox(height: 40,),
GestureDetector(
onTap: () async {
await auth.signIn(emailTextController.text.trim(), passwordTextController.text.trim(),context);
if(await auth.getCurrentUser(signedIn: true))
{
Navigator.pushNamed(context, Routes.welcomeScreen);
}

},
child: Container(
width: MediaQuery.of(context).size.width,
margin: const EdgeInsets.symmetric(horizontal: 18),
height: 53,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
color: AppColors.mediumBlueGrey,
border: Border.all(color: AppColors.mediumTeal,width: 2)
),
child: Center(
child: Text(AppString.loginText,
style: AppTextStyle.text4,),
),
),
),
const SizedBox(height: 20),
Text( AppString.orWithText,
style: AppTextStyle.text3),
const SizedBox(height: 20),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 18),
child: SizedBox(
height: 53,
child: TextButton(
onPressed: () async{
await auth.signInWithWebUI();
if(await auth.getCurrentUser(signedIn: true))
{
Navigator.pushNamed(context, Routes.welcomeScreen);
}
if (!mounted) return;
},
style: ButtonStyle(
side: MaterialStateProperty.all(
const BorderSide(color: AppColors.mediumTeal, width: 2)),
backgroundColor: MaterialStateProperty.all(AppColors.mediumBlueGrey),
foregroundColor: MaterialStateProperty.all(AppColors.mediumBlueGrey),
minimumSize: MaterialStateProperty.all(
Size(MediaQuery.of(context).size.width, 58)),
shape: MaterialStateProperty.all(RoundedRectangleBorder(
borderRadius: BorderRadius.circular(40.0))),
padding: MaterialStateProperty.all(
const EdgeInsets.symmetric(vertical: 14),
),
textStyle: MaterialStateProperty.all(AppTextStyle.text2)),
child: Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(
AppIcons.googlePng,
scale: 23,
),
const SizedBox(
width: 10,
),
Text(AppString.signInWithGoogleText,
style: AppTextStyle.text4,),
],
),
),
),
),
const SizedBox(height: 20),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(AppString.doesNotHaveText),
TextButton(
onPressed: (){
Navigator.pushNamed(context, Routes.signUpScreen);
},
child: const Text(AppString.signUpText,
style: TextStyle(color: AppColors.mediumTeal),)
),
],
),
],
),
),
),
)
)
);
}
}

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Output

Sign-Up Screen

class SignUpPage extends StatefulWidget {
const SignUpPage({Key? key, required this.title}) : super(key: key);
final String title;
@override
State<SignUpPage> createState() => _SignUpPageState();
}

class _SignUpPageState extends State<SignUpPage> {
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
final TextEditingController emailTextController = TextEditingController();
final TextEditingController passwordTextController = TextEditingController();
final TextEditingController cPasswordTextController = TextEditingController();
bool validate = false;
AWSAuthRepo auth = AWSAuthRepo();

void clearText()
{
emailTextController.clear();
passwordTextController.clear();
cPasswordTextController.clear();
}

@override
void initState() {
// TODO: implement initState
super.initState();

}

@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: (){
FocusScope.of(context).unfocus();
},
child: Scaffold(
backgroundColor:AppColors.lightBlueGrey,
appBar: AppBar(
automaticallyImplyLeading: false,
centerTitle: true,
title: Text(widget.title),
backgroundColor: AppColors.mediumTeal,
),
body: SingleChildScrollView(
child: Form(
key: _formKey,
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 32.0),
child: Column(
children: [
const SizedBox(height: 20,),
Text(AppString.signUpPageText,
style: AppTextStyle.text1),
const SizedBox(height: 40,),
SizedBox(
width: MediaQuery.of(context).size.width,
height: 60,
child: Center(
child:
GrayGetTextField(
hint: 'User Email',
obscure: false,
controller: emailTextController,
isVisible: false,
onValidate: CommonUtils.isValidateEmail,
valueDidChange: (String? value) {
if(validate){
_formKey.currentState!.validate();}
}, inputType: TextInputType.emailAddress,)
),
),
const SizedBox(height: 20,),
SizedBox(
width: MediaQuery.of(context).size.width,
height: 60,
child:Center(
child:
GrayGetTextField(
hint: 'Password',
obscure: true,
controller: passwordTextController,
isVisible: true,
onValidate: CommonUtils.isPasswordValid,
valueDidChange: (String? value) {
if(validate){
_formKey.currentState!.validate();}
}, inputType: TextInputType.text,)
),
),
const SizedBox(height: 20,),
SizedBox(
width: MediaQuery.of(context).size.width,
height: 51,
child:GrayGetTextField(
hint: 'Confirm Password',
obscure: true,
controller: cPasswordTextController,
isVisible: true,
onValidate: CommonUtils.isPasswordValid,
valueDidChange: (String? value) {
if(validate){
_formKey.currentState!.validate();}
}, inputType: TextInputType.text,),
),
const SizedBox(height: 40,),
GestureDetector(
onTap: () async {
if(_formKey.currentState?.validate() ?? false) {
if (_formKey.currentState!.validate() &&
cPasswordTextController.text !=
passwordTextController.text) {
CommonUtils.showSnackBar(context,
'Password not match');
return;
}
await auth.signUp(emailTextController.text.trim(),
passwordTextController.text.trim(), context);
if(await auth.getCurrentUser(signedIn: true))
{
Navigator.pushNamed(context, Routes.welcomeScreen);
}
if (!mounted) return;

}
},
child: Container(
margin: const EdgeInsets.symmetric(horizontal: 18),
width: MediaQuery.of(context).size.width,
height: 53,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
color: AppColors.mediumBlueGrey,
border: Border.all(color: AppColors.mediumTeal,width: 2)
),
child: Center(
child: Text(AppString.signUpText,
style: AppTextStyle.text4,)
),
),
),
const SizedBox(height: 20,),
Text( AppString.orWithText,
style: AppTextStyle.text3),
const SizedBox(height: 20),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 18.0),
child: SizedBox(
height: 53,
child: TextButton(
onPressed: ()async{
await auth.signInWithWebUI();
if(await auth.getCurrentUser(signedIn: true))
{
Navigator.pushNamed(context, Routes.welcomeScreen);
}
if (!mounted) return;
},
style: ButtonStyle(
side: MaterialStateProperty.all(
const BorderSide(color: AppColors.mediumTeal, width: 2)),
backgroundColor: MaterialStateProperty.all(AppColors.mediumBlueGrey),
foregroundColor: MaterialStateProperty.all(AppColors.mediumBlueGrey),
minimumSize: MaterialStateProperty.all(
Size(MediaQuery.of(context).size.width, 58)),
shape: MaterialStateProperty.all(RoundedRectangleBorder(
borderRadius: BorderRadius.circular(40.0))),
padding: MaterialStateProperty.all(
const EdgeInsets.symmetric(vertical: 14),
),
textStyle: MaterialStateProperty.all(AppTextStyle.text2)),
child: Row(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(
AppIcons.googlePng,
scale: 23,
),
const SizedBox(
width: 10,
),
Text(AppString.signUpWithGoogleText,
style: AppTextStyle.text4,
),
],
),
),
),
),
const SizedBox( height: 20,),
Row(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(AppString.haveAccountText),
TextButton(
onPressed: (){
Navigator.pushNamed(context, Routes.signInScreen);
},
child: const Text(AppString.loginText,
style: TextStyle(color: AppColors.mediumTeal),)
),
],
),
],
),
),
),
),
),
);
}
}

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Confirmation Page

class ConfirmationSignUP extends StatefulWidget {
const ConfirmationSignUP({Key? key}) : super(key: key);

@override
State<ConfirmationSignUP> createState() => _ConfirmationSignUPState();
}

class _ConfirmationSignUPState extends State<ConfirmationSignUP> {
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
final TextEditingController emailTextController = TextEditingController();
final TextEditingController confirmationTextController = TextEditingController();
bool validate = false;
@override
Widget build(BuildContext context) {
return GestureDetector(
onTap: (){
FocusScope.of(context).unfocus();
},
child: Scaffold(
backgroundColor: AppColors.lightBlueGrey,
appBar: AppBar(
automaticallyImplyLeading: false,
centerTitle: true,
title: Text("Confirmation Page"),
backgroundColor: AppColors.mediumTeal,
),
body:
SingleChildScrollView(
child: Center(
child: Form(
key: _formKey,
child: Column(
children: [
const SizedBox(height: 40,),
Text(AppString.confirmSignUpText,
style: AppTextStyle.text1),
const SizedBox(height: 70,),
Container(
width: MediaQuery.of(context).size.width,
padding: const EdgeInsets.symmetric(horizontal: 32),
height: 60,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
//color: AppColors.mediumBlueGrey
),
child:
GrayGetTextField(
hint: 'User Email',
obscure: false,
controller: emailTextController,
isVisible: false,
onValidate: CommonUtils.isValidateEmail,
valueDidChange: (String? value) {
if(validate){
_formKey.currentState!.validate();}
}, inputType: TextInputType.emailAddress,)
),
const SizedBox(height: 30,),
Container(
width: MediaQuery.of(context).size.width,
padding: const EdgeInsets.symmetric(horizontal: 32),
height: 60,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
//color: AppColors.mediumBlueGrey
),
child:
TextField(
controller: confirmationTextController,
decoration: const InputDecoration(
fillColor: AppColors.mediumBlueGrey,
filled: true,
border: InputBorder.none,
labelStyle: TextStyle(color: AppColors.mediumTeal),
hintText: 'Confirmation Code',
isDense: true,
contentPadding:
EdgeInsets.symmetric(horizontal: 12, vertical: 15),
),
)
),
SizedBox(height: MediaQuery.of(context).size.height*0.3,),
GestureDetector(
onTap: () async {
if (_formKey.currentState?.validate() ?? false)
{
if (confirmationTextController.text.isEmpty) {
CommonUtils.showSnackBar(context, 'Please Enter Confirmation Code');
return;}
else {
await AWSAuthRepo().signUpConfirmation(emailTextController.text.trim(), confirmationTextController.text.trim());
Navigator.pushNamed(context, Routes.welcomeScreen);
}
}
},
child: Container(
width: MediaQuery.of(context).size.width / 1.6,
height: 60,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(30),
color: AppColors.mediumTeal
),
child: Center(
child: Text(AppString.submitText,
style: AppTextStyle.text2,),
),
),
),
const SizedBox(height: 20),
],
),
),
),
)
),
);;
}
}

When we run the application, we ought to get the screen’s output like the underneath screen capture.

Home Screen

class Home extends StatefulWidget {

const Home({Key? key}) : super(key: key);
@override
State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
AWSAuthRepo auth = AWSAuthRepo();
final GlobalKey<FormState> _formKey = GlobalKey<FormState>();
final TextEditingController nameTextController = TextEditingController();
final TextEditingController phoneNoTextController = TextEditingController();

@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: AppColors.lightBlueGrey,
bottomNavigationBar: BottomAppBar(
color: AppColors.lightBlueGrey,
child: GestureDetector(
onTap: () async {
auth.signOut();
Navigator.pushNamed(context, Routes.signInScreen);
},
child: Container(
key: const Key("signOutButton"),
margin: const EdgeInsets.symmetric(horizontal: 32),
width: MediaQuery.of(context).size.width,
height: 60,
decoration: BoxDecoration(borderRadius: BorderRadius.circular(30),
color: AppColors.mediumTeal),
child: Center(
child: Text(AppString.signOutText,
style: AppTextStyle.text2,),
),),


Demo Video

Sign-up with Email and Password

Auth with Social Provider(Google)

Conclusion

In this article, We learn auth user management using AWS Amplify Studio via Email and Password, and Social Login with Gmail.

There are some useful run commands.

amplify configure
amplify init
amplify auth
amplify add auth
amplify push
amplify status

To know more details about these use the below link

https://docs.amplify.aws/cli/start/workflows/#optional-update-projects-using-latest-amplify-cli

AWS Amplify also provides rebuild SignIn and SignUp UI, you can use it.

amplify_authenticator | Flutter Package
The Amplify Flutter Authenticator simplifies the process of authenticating users by providing a fully-customizable flow…pub.dev


GitHub

You can get the full code on the below link

GitHub — RitutoshAeologic/aws_demo
A new Flutter project. This project is a starting point for a Flutter application. A few resources to get you started…github.com


❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


Reference :

https://docs.amplify.aws/lib/auth/getting-started/q/platform/flutter/

AWS Amplify Features | Front-End Web & Mobile | Amazon Web Services
With Amplify CLI and Libraries, add features such as auth, storage, data, AI/ML, and analytics to your app. Deploy web…aws.amazon.com


From Our Parent Company Aeologic

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

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

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

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

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

Assets Generated Dynamically In Flutter

0

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.

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table Of Contents

Introduction?

Add Dependency

Configuration

Conclusion

GitHub Link


Introduction?

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:

dev_dependencies:
build_runner:
flutter_gen_runner:

Install FlutterGen

$ flutter pub get

Use FlutterGen

$ flutter packages pub run build_runner build

Configuration:

FlutterGen generates dart files based on the key flutter and flutter_gen of pubsec. yaml. We will install it as part of build_runner.

Add build_runner and flutter_gen as part of your dev_dependencies in the pubsec.yaml file:

dev_dependencies:
build_runner:
flutter_gen_runner:

Run the command below in your root app directory to install FlutterGen:

$ flutter pub get

The default configuration can be found here:

name: auto_generated_assets_demo
description: A new Flutter project.
version: 1.0.0+1

environment:
sdk: '>=2.19.6 <3.0.0'
dependencies:
flutter:
sdk: flutter
cupertino_icons: ^1.0.2
flutter_svg: ^2.0.5

dev_dependencies:
flutter_test:
sdk: flutter
flutter_lints: ^2.0.0
build_runner: ^2.3.3
flutter_gen_runner: ^5.3.1

flutter_gen:
output: lib/resources/ # Optional (default: lib/gen/)
line_length: 80 # Optional (default: 80)

integrations:
flutter_svg: true
flare_flutter: true
rive: true

colors:
enabled: true
inputs:
- assets/colors/colors.xml
assets:
output:
enabled: true
package_parameter_enabled: true
style: camel-case

flutter:
uses-material-design: true
generate: true
assets:
- assets/icon/
- assets/images/

fonts:
- family: Domine
fonts:
- asset: assets/fonts/domine/Domine-Regular.ttf
- weight: 400
- asset: assets/fonts/domine/Domine-Medium.ttf
- weight: 500
- asset: assets/fonts/domine/Domine-SemiBold.ttf
- weight: 600
- asset: assets/fonts/domine/Domine-Bold.ttf
- weight: 700

Generate code for assets:

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:

import '../resources/assets.gen.dart';
import '../resources/fonts.gen.dart';
import '../resources/colors.gen.dart';
  • SVG
Assets.icon.google
.svg(color: ColorName.cranberry, height: 350)
  • Images
Assets.images.staging.image(),

When you change the location or name of your image, it will be enough to run the command again.

Conclusion:

You have gone through the type of assets and how they are accessed in Flutter using string paths. You are now able to install and use FlutterGen to:

  • Remove string references to assets throughout your app
  • Generate asset classes and static variables
  • Load your assets in a type-safe way
  • Customize the style of asset generation

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

You can check out FlutterGen on GitHub. We hope you enjoyed this tutorial!

GitHub – rahul-t-aeologic/auto_generated_assets_demo: Auto generated assets project
A new Flutter project. This project is a starting point for a Flutter application. A few resources to get you started…github.com


From Our Parent Company Aeologic

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

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

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

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

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


Binder — State Management in Flutter

0

It is a lightweight, yet powerful way to hold together your application states with your business logic which will be responsible for updating it.

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.

Table of Contents:-

Flutter — Introduction

State management

Installation

Code Implementation

Final Output

Conclusion

Github Link


Flutter — Introduction:-

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.

void main() => runApp(BinderScope(child: MyApp()));
  • LogicLoader() —

A widget that can be used to load resources when it’s inserted in the tree.

For example, you can use this widget to load data from the repository, the first time this widget builds.

Installation:-

  1. Getting started with Binder:-

To start using Binder in your Flutter project, you need to follow a few simple steps:

a. Add the Binder dependency in the “dependency” section of your project’s pubspec.yaml file.binder: ^0.4.0

b. Define your model classes representing different parts of your app’s state.

c. Create a Binder instance and bind your models to it.

d. Use the provided BinderScope widget to wrap the parts of your UI that depend on the state.

e. Access and modify the state using the BinderScope and the model instances.

Code Implementation:-

Let’s understand binder more descriptively. Below is the project code which has been developed using Binder.

main.dart:-

void main() {
runApp(const App());
}

class App extends StatelessWidget {
const App({
Key key,
this.mockHome,
}) : super(key: key);

Final Widget mockHome;

@override
Widget build(BuildContext context) {
return BinderScope(
child: MaterialApp(
title: 'Binder Demo App',
theme: ThemeData(
primarySwatch: Colors.blue,
visualDensity: VisualDensity.adaptivePlatformDensity,
),
debugShowCheckedModeBanner: false,
home: const HomeView(),
),
);
}
}

Logic.dart :-

final homeViewLogicRef = LogicRef((scope) => HomeViewLogic(scope));

final usersRef = StateRef(const <User>[]);

class HomeViewLogic with Logic, BusyLogic implements Loadable {
const HomeViewLogic(this.scope);

@override
final Scope scope;

UserRepository get _userRepository => use(userRepositoryRef);

@override
Future<void> load() async {
busy = true;
final users = await _userRepository.getUsers();
write(usersRef, users);
busy = false;
}
}

view.dart :-

final userCountRef = Computed((watch) {
return watch(usersRef).length;
});

class HomeView extends StatelessWidget {
const HomeView({
Key key,
}) : super(key: key);

@override
Widget build(BuildContext context) {
return BinderScope(
overrides: [
busyRef.overrideWith(false),
homeViewLogicRef.overrideWithSelf(),
],
child: LogicLoader(
refs: [homeViewLogicRef],
child: const BusyListener(
child: Scaffold(
backgroundColor: AppColors.bgColor,
// appBar: AppBar(
// title: Text('Home', style: AppTextStyles.extraLargeWhiteText()),
// ),
body: SafeArea(child: UserGridView()),
),
),
),
);
}
}

class UserGridView extends StatelessWidget {
const UserGridView({
Key key,
}) : super(key: key);

@override
Widget build(BuildContext context) {
return Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Padding(
padding: const EdgeInsets.all(20.0),
child: Text("Users", style: AppTextStyles.xExtraLargeBlackText()),
),
Expanded(
child: Padding(
padding: const EdgeInsets.all(8),
child: GridView.builder(
physics: const BouncingScrollPhysics(),
gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
crossAxisCount: 2,
mainAxisSpacing: 10,
crossAxisSpacing: 10,
),
itemCount: context.watch(userCountRef),
itemBuilder: (context, index) {
final user = context.watch(usersRef.select((users) => users[index]));
return BinderScope(
overrides: [currentUserRef.overrideWith(user)],
child: const UserCellView(),
);
},
),
),
),
],
);
}
}

class UserCellView extends StatelessWidget {
const UserCellView({
Key key,
}) : super(key: key);

@override
Widget build(BuildContext context) {
final name = context.watch(currentUserRef.select((user) => user.name));
final initials = name.initials;
return Card(
child: InkWell(

onTap: () {
final user = context.read(currentUserRef);
Navigator.of(context).push(
MaterialPageRoute<void>(
builder: (context) {
return BinderScope(
overrides: [currentUserRef.overrideWith(user)],
child: UserView(name: name),
);
},
),
);
},
child: Padding(
padding: const EdgeInsets.symmetric(horizontal: 8.0),
child: Column(
children: [
CircleAvatar(
radius: 30,
backgroundColor: AppColors.primaryColor,
child: Text(
initials,
style: AppTextStyles.largeNormalTextLora(),
),
),
const SizedBox(
height: 10,
),
Text(
name,
textAlign: TextAlign.center,
style: AppTextStyles.regularMediumText(),
),
],
),
),
),
);
}
}

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.

Clap 👏 If this article helps you.


Github link:

Find the source code of binder_demo:

GitHub – flutter-devs/binder_demo
A new Flutter project. This project is a starting point for a Flutter application. A few resources to get you started…github.com


From Our Parent Company Aeologic

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

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

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

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

We welcome 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.


Flutter: Building UI with Machine Learning capabilities

0

Machine Learning is a field of study that allows computers to learn without being explicitly programmed. However, we’ll see it further in brief.

If you’re looking for the best Flutter app development company for your mobile application then feel free to contact us at — support@flutterdevs.com.


Table of Contents:-

Machine Learning — Introduction

Flutter with Machine Learning

Installation

Create Model

Steps to create a model

Code Implementation

Final Output

Conclusion

Github Link


Machine Learning:-

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

<uses-permission android:name="android.permission.INTERNET" />

Create model:-

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.

Steps to create a model:-

— Go to https://teachablemachine.withgoogle.com/

— 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

flutter:
uses-material-design: true
assets:
- assets/images/
- assets/labels.txt
- assets/model_unquant.tflite

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.

Code Implementation:-

main. dart

void main() =>
runApp(const MaterialApp(
home: MyApp(),
debugShowCheckedModeBanner: false,
));

MyApp.dart

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.

Clap 👏 If this article helps you.


GitHub Link:-

GitHub – flutter-devs/flutter_ml at master
A new Flutter project. This project is a starting point for a Flutter application. A few resources to get you started…github.com


From Our Parent Company Aeologic

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

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

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

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

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