Google search engine
Home Blog Page 212

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.

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.

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.

Related: Generate Strong Random Password In Flutter

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.


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.

Related: SMS Using Twilio In Flutter

Related: Using SharedPreferences in Flutter

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.


Complete Guide to AWS Amplify Auth in Flutter 2026

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.

Related: AWS Amplify Analytics with Flutter

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.

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.

Related: SMS Using Twilio In Flutter

Related: Using SharedPreferences in Flutter

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.


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.

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.


How to Build Flutter UI with Machine Learning in 2026

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.

Related: Flutter Apps with AI and Machine Learning

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.


AWS Amplify Analytics with Flutter

0

This blog will explore the AWS Amplify Analytics with Flutter. We will also implement a demo program, and learn how to use AWS Amplify Analytics it 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 Content

AWS Amplify Libraries

Amplify Analytics

Uses

Integration With Flutter

Installation

Pre-requisite

Code Implementaion

Final Output

Conclusion

GitHub Link

Reference


AWS Amplify Libraries:-

The Amplify open-source client libraries are designed to simplify and streamline the interaction between mobile and web developers and their AWS backend resources. These libraries offer easy-to-use interfaces for various categories of AWS cloud operations, making it convenient for developers to integrate and interact with their backend services.

With the Amplify libraries, developers can focus on building their applications without worrying about the intricacies of managing AWS services directly. The libraries provide a set of pre-built functions and APIs that abstract away the complexity of interacting with AWS services, allowing developers to perform common tasks and operations with just a few lines of code.

Whether developers are working with new backends created using the Amplify Command Line Interface (CLI) or existing backend resources, the Amplify libraries can be utilized to simplify the integration and communication process. This flexibility enables developers to seamlessly work with their preferred backend setup and leverage the power of AWS services without needing deep knowledge of AWS-specific APIs or configurations.

Amplify Analytics:-

The Analytics category in Amplify provides functionality to collect analytics data for your application. It offers built-in integration with Amazon Pinpoint and Amazon Kinesis (currently available only in the Amplify JavaScript library).

By using the Analytics category, you can track and gather valuable insights about user behavior, engagement, and usage patterns within your app. This data can be used to make informed decisions, improve user experiences, and optimize your app’s performance.

The Analytics category relies on Amazon Cognito Identity pools to identify and differentiate users within your app. It allows you to collect data from both authenticated and unauthenticated users, providing a comprehensive view of user interactions.

Uses:-

— Capturing User Events One of the primary benefits of Amplify Analytics is its ability to capture user events. You can track various events in your app, such as screen views, button clicks, form submissions, and more. By logging these events, you can understand how users navigate through your app and identify areas for improvement.

The Amplify Flutter library provides a AnalyticsRecordEvent API that allows you to log custom events with associated attributes and metrics. For example, you can log an event when a user adds a product to their cart and include attributes such as the product ID, name, and price. These events and associated data are then sent to the Amplify Analytics service for analysis.

— User Session Tracking Amplify Analytics also enables you to track user sessions, which provide valuable insights into how users engage with your app over time. A session represents a period of user activity within your app, typically starting when the app is launched and ending when the app is closed or put into the background.

The Amplify Flutter library automatically tracks user sessions and records session-related data, such as the session start time, duration, and the number of events logged during the session. This information can help you understand user engagement patterns and identify trends or anomalies.

— User Demographics and Segmentation Understanding your app’s user demographics is crucial for tailoring your app’s features and content to your target audience. Amplify Analytics allows you to collect user demographic data, including attributes such as age, gender, location, and language preferences.

By leveraging this demographic data, you can segment your user base and gain insights into how different user groups interact with your app. For example, you can analyze the behavior of users from different regions or age groups to identify specific usage patterns and preferences. This information can guide your decision-making process when designing new features or optimizing existing ones.

— Data Visualization and Analysis AWS Amplify Analytics provides a comprehensive set of tools for visualizing and analyzing user behavior data. The Amplify Console, a web-based management console, allows you to view real-time metrics and create custom dashboards to monitor your app’s key performance indicators (KPIs).

Integration with Flutter:-

Integrating AWS Amplify Analytics into a Flutter app is a straightforward process. First, you need to set up an Amplify project and configure the Analytics category. This involves creating an Amplify project, adding the Analytics category, and configuring the necessary settings such as the Amazon Pinpoint project.

Once the setup is complete, you can use the Amplify Flutter library to start tracking user events and sending them to the Amplify Analytics service. The library provides a set of APIs that allow you to log custom events, record user sessions, and track user demographics. These APIs are designed to be simple and intuitive, making it easy to instrument your app with analytics capabilities.

Installation:-

There are a few packages that need to be imported into our Flutter project to implement Amplify Analytics.

Add packages to the dependency block, like below,

dependencies:
amplify_flutter: ^0.6.0
amplify_auth_cognito: ^0.6.0
amplify_authenticator: ^0.2.0
amplify_storage_s3: ^0.6.0
amplify_api: ^0.6.0

Pre-requisites:-

Before starting make sure of these steps.

  • Install the latest version of Flutter.
  • Create an account on AWS Amplify if you do not have one.
  • Create a user and generated a security key.

We need to setup amplify in our project, to install run the following command in your terminal

npm install -g @aws-amplify/cli

Afterward, initialize amplify in the flutter project. To do so follow the below steps:

— To ensure proper installation of the Amplify CLI version, execute the following command:

amplify --version

— To connect to the AWS cloud and initialize Amplify, use the following command:

amplify init

Once you’re done, you will find a file automatically created for configurations of amplify, named ‘amplifyconfiguration. dart’. This will help connect your project to AWS Amplify.

— To initialize Amplify, you need to call the Amplify.configure() method. Here’s an example of how to initialize Amplify:

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

class MyApp extends StatefulWidget {
...

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

void _configureAmplify() async {
try {
await Amplify.addPlugin(AmplifyAuthCognito());
await Amplify.addPlugin(AmplifyStorageS3());
await Amplify.addPlugin(
AmplifyAPI(modelProvider: ModelProvider.instance));
await Amplify.configure(amplifyconfig);
} on Exception catch (e) {
print('Error configuring Amplify: $e');
}
}
}

...
}

In the above, the _configureAmplify() function is called to initialize Amplify. The method uses the Amplify.addPlugin() method to add the required plugins (such as AmplifyAuthCognito and AmplifyDataStore) to Amplify. It then calls Amplify.configure() with the amplifyconfig object to provide the necessary configuration.

Code Implementation:-

  • main.dart:-
void main() {
runApp(const MyApp());
}

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

@override
State<MyApp> createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return Authenticator(
child: MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.blue,
useMaterial3: true),
home: const MyHomePage(title: 'Flutter Amplify Quickstart'),
builder: Authenticator.builder(),
));
}

@override
void initState() {
super.initState();
_configureAmplify();
}
void _configureAmplify() async {
try {
await Amplify.addPlugin(AmplifyAuthCognito());
await Amplify.addPlugin(AmplifyStorageS3());
await Amplify.addPlugin(
AmplifyAPI(modelProvider: ModelProvider.instance));
await Amplify.configure(amplifyconfig);
} on Exception catch (e) {
print('Error configuring Amplify: $e');
}
}
}

class MyHomePage extends StatefulWidget {
const MyHomePage({super.key, required this.title});

final String title;

@override
State<MyHomePage> createState() => _MyHomePageState();
}

class _MyHomePageState extends State<MyHomePage> {
final _nameController = TextEditingController();
final _locationController = TextEditingController();
final _languageController = TextEditingController();
UserProfile? _userProfile;

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

void _getUserProfile() async {
final currentUser = await Amplify.Auth.getCurrentUser();
GraphQLRequest<PaginatedResult<UserProfile>> request = GraphQLRequest(
document:
'''query MyQuery { userProfilesByUserId(userId: "${currentUser.userId}") {
items {
name
location
language
id
owner
createdAt
updatedAt
userId
}
}}''',
modelType: const PaginatedModelType(UserProfile.classType),
decodePath: "userProfilesByUserId");
final response = await Amplify.API.query(request: request).response;

if (response.data!.items.isNotEmpty) {
_userProfile = response.data?.items[0];

setState(() {
_nameController.text = _userProfile?.name ?? "";
_locationController.text = _userProfile?.location ?? "";
_languageController.text = _userProfile?.language ?? "";
});
}
}

@override
Widget build(BuildContext context) {
return Stack(
children: [
Image.asset(
"assets/background.jpg",
height: MediaQuery.of(context).size.height,
width: MediaQuery.of(context).size.width,
fit: BoxFit.cover,
),
Scaffold(
backgroundColor: Colors.transparent,
appBar: AppBar(
// Here we take the value from the MyHomePage object that was created by
// the App.build method, and use it to set our appbar title.
title: Text(widget.title),
backgroundColor: Colors.transparent,
foregroundColor: Colors.white,
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Card(
margin: const EdgeInsets.symmetric(horizontal: 30),
child: Padding(
padding: const EdgeInsets.all(30),
child: Column(
mainAxisSize: MainAxisSize.min,
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Padding(
padding: const EdgeInsets.symmetric(vertical: 20),
child: Text(
'User Profile',
style: Theme.of(context).textTheme.titleLarge,
)),
const ProfilePicture(),
TextField(
decoration: const InputDecoration(labelText: "Name"),
controller: _nameController,
),
TextField(
decoration:
const InputDecoration(labelText: "Location"),
controller: _locationController,
),
TextField(
decoration: const InputDecoration(
labelText: "Favourite Language"),
controller: _languageController,
)
],
),
))),
floatingActionButton: FloatingActionButton(
onPressed: _updateUserDetails,
tooltip: 'Save Details',
child: const Icon(Icons.save),
),
)
],
);
}

Future<void> _updateUserDetails() async {
final currentUser = await Amplify.Auth.getCurrentUser();

final updatedUserProfile = _userProfile?.copyWith(
name: _nameController.text,
location: _locationController.text,
language: _languageController.text) ??
UserProfile(
userId: currentUser.userId,
name: _nameController.text,
location: _locationController.text,
language: _languageController.text);

final request = _userProfile == null
? ModelMutations.create(updatedUserProfile)
: ModelMutations.update(updatedUserProfile);
final response = await Amplify.API.mutate(request: request).response;

final createdProfile = response.data;
if (createdProfile == null) {
safePrint('errors: ${response.errors}');
}
}
}

You’ll find the entire code file in the GitHub Link section below.

Final Output:-

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

Conclusion:-

In this article, we have delved into the implementation of AWS Amplify Analytics in our Flutter application. By incorporating this powerful tool, we can effortlessly track user events, enabling us to gain valuable insights into user behavior and app performance.

Now that you have gained an understanding of the process, feel free to customize and experiment with your unique approach. Unleash your creativity and explore the vast potential of AWS Amplify Analytics in optimizing your app’s success.

❤ ❤ 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 Project —

GitHub – flutter-devs/aws_analytics_demo: AWS Amplify Analytics
AWS Amplify Analytics. Contribute to flutter-devs/aws_analytics_demo development by creating an account on GitHub.github.com


Reference:-

📃 AWS Amplify Docs — https://docs.amplify.aws/lib/analytics/getting-started/q/platform/js


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.

Related: Firebase Analytics In Flutter

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.


Step-by-Step Flutter UPI Payment Gateway Integration 2026

0

This blog will explore the Integrate UPI Payment Gateway Using SDK In Flutter. We will also implement a demo program, and learn how to integrate UPI payment gateway using SDK 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

Understanding UPI and its significance

Choosing the Right UPI SDK

Key features of UPI Payment Gateway

Setting up your flutter project

Gradle setup

Installing the UPI SDK

Initialising UPI payment

EasyUpiPaymentModel

Parameters Of EasyUpiPaymentModel

TransactionDetailModel

Parameters Of TransactionDetailModel

Final Output

Conclusion

Github Link


Introduction:-

In today’s fast-paced digital world, providing seamless and secure payment options within a mobile app is crucial for enhancing user experience and driving business growth. The Unified Payments Interface (UPI) has revolutionized digital payments in India, offering a simple and efficient way for users to transfer funds and make payments instantly. By integrating a UPI payment gateway into your Flutter app, you can enable your users to make hassle-free transactions, whether for purchasing products, paying bills, or transferring money.

This comprehensive article will walk you through the process of integrating a UPI payment gateway into your Flutter app. Whether you’re a seasoned developer or just getting started with Flutter, this article will provide you with step-by-step instructions and best practices to implement UPI payments successfully. By the end of this article, you’ll have a deep understanding of how to create a seamless payment experience for your users while ensuring the highest standards of security.

Understanding UPI and its Significance:

Unified Payment Interface (UPI) is a groundbreaking payment system that allows users to link multiple bank accounts to a single mobile application. This enables seamless fund transfers and transactions between individuals and businesses, eliminating the need for traditional banking methods.

UPI operates 24/7, ensuring real-time transfers, and has gained immense popularity due to its simplicity and security. Integrating UPI into your Flutter app empowers users to make hassle-free payments, boosting customer satisfaction and engagement. This section will provide a comprehensive overview of UPI, its functioning, and why it’s a game-changer for digital payments.

Choosing the Right UPI SDK:

Selecting a suitable UPI Software Development Kit (SDK) is vital. Compare SDK options such as Paytm, Razorpay, and BharatPe, evaluating factors like integration complexity, documentation quality, community support, and compatibility with your Flutter project.

Key features of UPI Payment Gateway:

  • Seamless Transactions: Users can make payments seamlessly within your Flutter app, reducing friction and enhancing the overall user experience.
  • Wide Payment Acceptance: UPI supports a wide range of use cases, including person-to-person transfers, bill payments, online shopping, and more, making your app versatile and accommodating various transaction types.
  • Real-Time Processing: UPI payments are processed in real-time, allowing users to receive instant confirmation and updates about the status of their transactions.
  • Enhanced Security: By leveraging a reputable UPI SDK, you ensure that sensitive financial data is encrypted and protected, offering a secure payment environment for users.
  • User-Friendly Interface: Your app can provide a user-friendly payment interface where users can easily input payment details, review transactions, and initiate payments without hassle.
  • Payment Status Updates: Users receive immediate updates on the success or failure of their transactions, ensuring transparency and reducing uncertainty.
  • Convenient Payment Methods: UPI allows users to link multiple bank accounts to a single app, giving them the flexibility to choose their preferred payment source.
  • QR Code Support: UPI supports QR code payments, enabling users to scan QR codes to initiate payments quickly and effortlessly.
  • Cross-Bank Compatibility: UPI enables transactions between different banks, making it easy for users with accounts across various banks to transact seamlessly.
  • Error Handling: The UPI SDK can provide robust error handling mechanisms, helping to manage potential issues during the payment process and providing users with clear error messages.

Setting Up Your Flutter Project:

Initiate your Flutter project by creating a new app or modifying an existing one. Ensure that Flutter and Dart are installed, and set up your project with the required dependencies in the pubspec.yaml file.

Gradle Setup:

  • In build.gradle of the app module, include this below dependency to import the EasyUpiPayment library in the app.
dependencies {
implementation "dev.shreyaspatil.EasyUpiPayment:EasyUpiPayment:3.0.3"
}
  • Furthermore, within the debugConfig, update the minSdkVersion to 19.
defaultConfig {
minSdkVersion 19
}

Installing the UPI SDK:

Integrate your chosen UPI SDK into your project by adding the SDK dependency to the pubspec.yaml file.

dependencies:
flutter:
sdk: flutter

easy_upi_payment: <latest version>
  • Run the flutter pub get command to install the dependency, making the SDK’s functionalities available in your Flutter app.

Initialise UPI payment:

The startPayment() a method is likely designed to initiate a UPI payment transaction within a Flutter app.

ref.read(mainStateProvider.notifier).startPayment(
EasyUpiPaymentModel(
payeeVpa: payeeVpaController.text,
payeeName: payeeNameController.text,
amount: double.parse(amountController.text),
description: descriptionController.text,
),
);
  • We pass an object of EasyUpiPaymentModel as a parameter of the startPayment() method.

EasyUpiPaymentModel:

class EasyUpiPaymentModel {

final String payeeVpa;
final String payeeName;
final String? payeeMerchantCode;
final String? transactionId;
final String? transactionRefId;
final String? description;
final double amount;

const EasyUpiPaymentModel({
required this.payeeVpa,
required this.payeeName,
required this.amount,
required this.description,
this.payeeMerchantCode,
this.transactionId,
this.transactionRefId,
});
}

Parameters Of EasyUpiPaymentModel:

  1. payeeVpa (Virtual Payment Address): The recipient’s UPI identifier, often in the format username@upi. This is similar to an email address but used for payments.
  2. payeeName : It takes the name of the payee/recipient like the User Name.
  3. amount: The amount of money to be transferred in the transaction.
  4. transactionRefId (Optional): A reference string or ID associated with the transaction for tracking and reconciliation purposes.
  5. transactionId (Optional): This field is used in Merchant Payments generated by PSPs. If provided null then it uses [DateTime.now().microsecondsSinceEpoch]
  6. payeeMerchantCode (Optional): A code that identifies the merchant initiating the payment, often used for business-specific purposes.
  7. description (Optional): A short description or note about the payment.

We get an object of TransactionDetailModel as the return from the startPayment() method.

Future<TransactionDetailModel?> startPayment(
EasyUpiPaymentModel easyUpiPaymentModel,
) {
throw UnimplementedError('startPayment() has not been implemented.');
}

TransactionDetailModel:

class TransactionDetailModel {
final String? transactionId;
final String? responseCode;
final String? approvalRefNo;
final String? transactionRefId;
final String? amount;

const TransactionDetailModel({
required this.transactionId,
required this.responseCode,
required this.approvalRefNo,
required this.transactionRefId,
required this.amount,
});
}

Parameters Of TransactionDetailModel:

  1. transactionId: A unique identifier assigned to the payment transaction.
  2. responseCode : A numerical code that represents the outcome of the payment. Different codes usually correspond to different types of results, such as success, failure, or other specific scenarios.
  3. approvalRefNo: A reference number provided by the payment gateway or bank to identify the approval of the transaction.
  4. transactionRefId : A reference ID assigned to the transaction, which might be useful for tracking and reconciliation purposes.
  5. amount : The amount of money involved in the transaction.

We have the flexibility to adapt and utilize these fields as per our specific -requirements within the user interface. Hence, the UPI payment service has been seamlessly integrated into our Android app, ensuring a smooth and efficient user experience 😃.

You’ll find the entire code in the GitHub Link mentioned below.

Final Output:

As we run the application, this is what we get as our final output.


Conclusion:

In this article, we’ve explored the process of seamlessly incorporating UPI payment services into our Flutter app. Hope you found the article useful to you😃.

❤ ❤ 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/upi_pay_app
Contribute to flutter-devs/upi_pay_app development by creating an account on GitHub.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.

Related: Stripe Payment In Flutter

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.


3D Models In Flutter

0

3D models are those model which has 3 measurements length, width, and depth. These models give an incredible user experience when utilized for different purposes. What’s more, adding such a sort of perception to your application will be extremely useful for the user, helping your application develop and attract an enormous crowd.

In this article, we will 3D Models In Flutter. We will implement a 3d model demo program and show 3D models in the glTF and GLB formats using the model_viewer_plus package in your Flutter applications.

  • For Model Viewer Plus

model_viewer_plus | Flutter package
A Flutter widget for rendering interactive 3D models in the glTF and GLB formatspub. dev

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

Features

Parameters

Implementation

Code Implement

Code File

Conclusion



Introduction:

A Flutter widget for delivering interactive 3D models in the glTF and GLB designs. The widget inserts Google’s <model-viewer> web part in a WebView. The 3D model shows a 3D picture, and the user ought to turn toward any path for the watcher.

Demo Module :

This demo video shows how to create a 3d model in a flutter. It shows how the 3d model will work using the model_viewer_plus package in your Flutter applications. It shows 3D models in the glTF and GLB format and rotates 360° degrees by mouse, hand touch, and auto-rotate. It will be shown on your device.

Features:

There are features of the model viewer plus:
  • > It renders glTF and GLB models. (Also, USDZ models on iOS 12+.)
  • > It Supports animated models with a configurable auto-play setting.
  • > It optionally supports launching the model into an AR viewer.
  • > It optionally auto-rotates the model with a configurable delay.
  • > It supports a configurable background color for the widget.

Parameters:

There are some parameters of the model viewer are:
  • > src: This parameter is used for the URL or path to the 3D model. This parameter is required. Only glTF/GLB models are supported.
  • > alt: This parameter is utilized to design the model with custom content that will portray the model to watchers who utilize a screen reader or, in any case, rely upon an extra semantic setting to comprehend what they are seeing.
  • > autoRotateDelay: This parameter sets the deferral before auto-revolution starts. The configuration of the worth is a number in milliseconds. The default is 3000.
  • > iosSrc: This parameter is used to the URL to a USDZ model, which will be used on supported iOS 12+ devices via AR Quick Look.
  • > arScale: This parameter is utilized to control the scaling conduct in AR mode in Scene Viewer. Set to “fixed” to incapacitate the model’s scaling, which sets it to be at 100% scale consistently. Defaults to “auto,” which permits the model to be resized.

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

model_viewer: ^0.8.1

Step 2: Add the assets

assets:
- assets/

Step 3: Import

import 'package:model_viewer_plus/model_viewer_plus.dart';

Step 4: Run flutter packages get in the root directory of your app.

Step 5: AndroidManifest.xml (Android 9+ only)

android/app/src/main/AndroidManifest.xml

To utilize this widget on Android 9+ devices, your application should be allowed to make an HTTP association with http://localhost:XXXXX. Android 9 (API level 28) changed the default forandroid:usesCleartextTrafficfrom true to false.

<application android:name="${applicationName}" 
android:icon="@mipmap/ic_launcher" 
android:label="example"
android:usesCleartextTraffic="true">

Step 6: app/build.gradle (Android only)

Change minSdkVersion to 21.
defaultConfig {    minSdkVersion 21}

Step 4:Info.plist (iOS only)

To enable the widget on iOS, add a boolean property named “io.flutter.embedded_views_preview” to your app’s ios/Runner/Info.plist file with the value “YES”.

<key>io.flutter.embedded_views_preview</key>  <true/>

How to implement code in dart file :

You need to implement it in your code respectively:

Create a new dart file called demo_view.dart inside the lib folder.

In the body, we will add ModelViewer(). Inside, we will add a backgroundColor for the model viewer; src means the user adds URL and assets only glTF/GLB models are supported.

ModelViewer(
        backgroundColor: Colors.teal[50]!,
        src: 'assets/table_soccer.glb',
        alt: "A 3D model of an table soccer",
        autoPlay: true,
        autoRotate: true,
        cameraControls: true,
      ),

We will add alt means configures the model with custom text that will describe the model to viewers who use a screen reader; autoplay means if this is true and a model has animations, an animation will automatically begin to play when this attribute is set. The default is false. We will add autoRotate means it enables the auto-rotation of the model. We will add cameraControls which enables controls via mouse/touch when in flat view.

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:model_viewer_plus/model_viewer_plus.dart';

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

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

class _DemoViewState extends State<DemoView> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text("Flutter 3D Model Viewer Demo"),
        automaticallyImplyLeading: false,
        backgroundColor: Colors.black,
        centerTitle: true,
      ),
      body: ModelViewer(
        backgroundColor: Colors.teal[50]!,
        src: 'assets/table_soccer.glb',
        alt: "A 3D model of an table soccer",
        autoPlay: true,
        autoRotate: true,
        cameraControls: true,
      ),
    );
  }
}

Conclusion:

In the article, I have explained the 3D Model basic structure in a flutter; you can modify this code according to your choice. This was a small introduction to 3D Model On User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information to try up the 3D Model in your flutter projects. We will show you what the Introduction is?. Some model viewer plus features, and parameters, make a demo program for working 3D Models and show 3D models in the glTF and GLB format and rotate 360° degrees by mouse, hand touch, and auto-rotate using the  model_viewer_plus package in your flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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.


Related: SMS Using Twilio In Flutter

Related: Using SharedPreferences in Flutter

Need expert help building your Flutter app? Talk to FlutterExperts for architecture, development, and consulting support.