Google search engine
Home Blog Page 48

Face Detection In Flutter

0

Hello Everyone I’m Back again with an exciting article where in we will be developing a flutter application able to detect images using firebase ml kit in our flutter apps .


firstly we will set up the firebase project -:

  • : Go to https://firebase.google.com/ and set up anew project.
  • : After that add in your app and download google-services.json.
  • : Add the lines in build.gradle and then you are done setting up firebase project.

Now we will work with what packages we need in the app :

  • image_picker
  • firebase_ml_vision

These 2 packages are required to work make this particular app

Now, we will go into detail how it works, so Firebase ml_kit has many modals like textRecognizer() , imageLabeler() , faceDetector() etc

Such modals are used to do various tasks (usually self explanatory), We will work with one of these modals to make a face detector app

So the basic idea of app will be for user to select an image from gallery and then we will check the images for faces using firebase_ml_vision package’s faceDetector().

So after your boilerplate code is ready we can start working on getting an image from users gallery,

var imageFile = await ImagePicker.pickImage(source: ImageSource.gallery);

This one line of code allows us to open gallery on click of a button, and we have applied await so that it will wait till the user picks one image,

So onto the next step, we need to convert what we got from image into a FirebaseVisionImage and we can use the .fromFile function from it, which will convert the file image into a firebaseVisionImage type

FirebaseVisionImage fbVisionImage = FirebaseVisionImage.fromFile(imageFile);

After we have a firebaseVisionImage by converting the image picked by user, we will need to initialize a faceDetector which will be done by

FaceDetector faceDetector = FirebaseVision.instance.faceDetector();

Alright after getting the instance of a FaceDetector we can finally work on our logic for the face detection

So we will require a list of Type Face.

Well Face class has many variables such as bindingBox , headEulerAngleY, headEulerAngleZ, leftEyeOpenProbability, rightEyeOpenProbability, we are only going to work with bindingBox which will give us a Rectangle or rather the coordinates of a rectangle around a face, which is what we will use to create a box around that face to show in an image that the rectangular box represents a face of a person

So to do this we need to first let our faceDetector isntance process the firebaseVisionImage and then return to us a list of face.

List<Face> listOfFaces = await faceDetector.processImage(fbVisionImage);

await once again here is important cause it will take time for it to go through the whole image and give us a list of all the possible faces in it.

after getting the listOfFaces, we will then use a simple for loop to get all the bindingBox from it. and then put them into another List which will contain a rectangles, since bindingBox gives us a rectangle.

List<Rect> rectArr = new List();
for (Face face in listOfFaces) {
rectArr.add(face.boundingBox);
}

Note : keep the rectArr outside of this function

So, now we have a list of rectangles that should be drawn on a face, what we need to do now is to simply convert an image into a ui.Image

So we will do that by using the readAsByteSync property of imageFile

var bytesFromImageFile = imageFile.readAsBytesSync();

Now we are going to use decodeImageFromList to get an image from a list of bytes of an image file

You will need to import dart ui as ui

import 'dart:ui' as ui;

After you are done with that, make an ui.Image

ui.Image image;

Note : declare image outside of the function as well

decodeImageFromList(bytesFromImageFile).then((img) {
setState(() {
image = img;
});
});

So after this we are done, with the hard part, now we will move onto the CustomPainter part.

class Painter extends CustomPainter {
Painter(@required this.rect, @required this.image);

final List<Rect> rect;
ui.Image image;

@override
void paint(Canvas canvas, Size size) {
var paint = Paint()
..color = Colors.red
..style = PaintingStyle.stroke
..strokeWidth = 7;

if (image != null) {
canvas.drawImage(image, Offset.zero, paint);
}
for (var i = 0; i <= rect.length - 1; i++) {
canvas.drawRect(rect[i], paint);
}
}

@override
bool shouldRepaint(oldDelegate) {
return true;
}
}

We have not done much here just make a class that extends custom painter and its constructor takes 2 parameters first is the ui.Image and the second is List<Rect> a list of rectangles, then we have a method called void paint, which is the main method where you draw,

To draw you first need to declare paint() then give it values such as the width of its stroke and size of the brush, the color of the brush etc, After that we check if the image is empty or not if its not then we tell the canvas to draw the image by using canvas.drawImage() method which takes 3 parameters, one is image which we get when we call painter, second is the offset, we set it to 0, third is the paint we declared earlier.

After drawing the image we now draw the rectangles using another loop and this time we use canvas.drawRect() and in it we pass the rect we get when we call the painter class and the paint.

With this you are almost ready, the final touch up is calling the painter method

For this in the build method we will put this sizedBox as a child

FittedBox(
child: SizedBox(
height: image == null ? height : image.height.toDouble(),
width: image == null ? width : image.width.toDouble(),
child: CustomPaint(
painter: Painter(rectArr, image),
),
),
),

So you must be asking why use fittedbox and sizedBox, well the answer is simple when flutter draws the image you will see the image as magnified and wont be fully contained inside your phone so to fix that we will need to give it bounded height and width and make it fit inside your device.

This will enable user to see the full image in the device.

With that piece of code we are finally done, don’t forget to wrap all the other code in a function and add a FAB that will help us pick images.

See the following gif to get in familiar with the application :

demo gif

For any help, let me know in the comments below, I will try my best to help you out ASAP. Let’s meet in the next article.


From Our Parent Company Aeologic

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

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

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

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

FocusNode in Flutter

0

Introduction :

FocusNode basically focuses on the keyboard event. Let’s suppose you want to control the TextFormField widget as soon as the user taps on it, then you use FocusNode. So, FocusNode class is basically an object that can be used to obtain keyboard focus and to handle keyboard events.

Before starting our blog lets quickly access what you will load on your memory after reading this blog

Demo Module

Before starting our blog lets quickly access what you will load on your memory after reading this blog


Table of Content

:: Implementing FocusNode in Forms

:: Creating of FocusNode

:: Usage of FocusNode in a TextFormField

:: Focus a text field when a button is tapped

:: Focus a text field as soon as an application starts

:: Passage of focus on next TextFormField after tapping


Implementing FocusNode in Forms

What is the use of FocusNode?

As we all know that there are many input type TextFormField in our form filling process, we have to input many details in different text area according to its requirement.

When our application has many TextFormFieldand the one which is selected and accepting an input from the user is said to have in a “focus” state. After providing an input to a focused TextFormField our focus now moves to another or says to the next TextFormField area. Here to implement such processes on focusing our selected TextFormField we use FocusNode.

How to focus on a TextFormField when a button is tapped?

Following steps to be performed to focus on a TextFormField

  1. Create a FocusNode.

2. Pass the FocusNode .

3. Give focus to the next TextFormFieldwhen the button is tapped.

How to create a FocusNode?

As you can see above image use the following steps to create a FocusNode instance inside a initState() method of a state class, and clean it up in a dispose() method.

Here we have created a five focus node instance for a different focus area.

How to pass FocusNode to a TextFormField ?

TextFormField(
autofocus: true,
focusNode: fname,
keyboardType: TextInputType.text,
enabled: true,
textInputAction: TextInputAction.next,
decoration: InputDecoration(
labelText: 'First Name',
hintText: 'Enter your first name',
border: OutlineInputBorder(
borderSide: BorderSide(color: Colors.teal),
),
),
onFieldSubmitted: (term) {
fname.unfocus();
FocusScope.of(context).requestFocus(lname);
},
)

Here we have used an instance fname of FocusNode in the focusNode property to get focus as soon as the user taps on this Textfield.

How to enable focus on the first TextFormField as an application starts or gets visible ?

We will set the autofocus property as true on that input area or TextFormFieldarea as you can see in the above example. For better understanding look down at an image.

To show the keyboard action when the TextFormFieldis focused we use textInputAction property in the TextFormFeild widget.

Example:

How to pass focus to the next TextFormField when the button is tapped ?

We will use the onFieldSubmitted property inside the TextFormField widget to get unfocus from the current focus TextFormField and get focus on the next TextFormField as soon as the button is pressed or when the keyboard next or done input type is pressed.

In the above example, we have used fname.unfocus() method to get unfocus from the firstTextFormFieldarea of an instance named fname as soon as the button is tapped.

As soon as the button is tapped we have successfully unfocused from the current TextFormFieldbut now we have to move our focus to the next TextFormFieldif available we will use:

FocusScope.of(context).requestFocus(lname)

so as to request our focus on the next TextFormField. We will move to the next TextFormFieldwith the help of the instance, we have created for the next TextFormFieldi.e lname in the above example.

main.dart file :

https://gist.github.com/SooRaj-99/77f625d8bfa68791347b66ee32dc8e3d#file-min-dart

Resources :

FocusNode class
An object that can be used by a stateful widget to obtain the keyboard focus and to handle keyboard events. Please see…api.flutter.dev

Focus and text fields
When a text field is selected and accepting input, it is said to have “focus.” Generally, users shift focus to a text…flutter.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.

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

From Our Parent Company Aeologic

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

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

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire 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

Flutter Bloc State Management

A flutter bloc state management series that will walk you through from all the basics of streams to advance state management tools like flutter_bloc/bloc package


Let’s start by understanding what we mean by state management and why should we care about it in the first place.

What Exactly Is State management ?

In simple words, state means data or the current information the user can see or manipulate.

For eg: Interface controls such as text fields, OK buttons, radio buttons, etc. To maintain these state of data like weather a button is pressed or not what is the current text in the text field or is a toggle button on or off, These data which user generally see or interacts with or generates on some event is called the state and the term used for maintaining all these information(state) is called state management.

The problem :

State management can become very messy when the application grows, simple tools like setState in flutter can’t be the solution for managing large changes at once and tools like inherited widget can create a lot of boilerplate code.

The Solution :

To overcome the above problem we can simply use tools like flutter_bloc/bloc these packages are created by the community are pretty useful for reducing boilerplate code and can be very easy to implement.

Before going deep into the flutter_bloc package we need to make our basics clear these basics includes :

  • :: streams
  • :: cubit
  • :: bloc

Streams :

A stream is a sequence of asynchronous data. Streams are just like water hose which have a sink and a drain, Which we can use to provide and retrieve data from streams. To fully understand the concept of bloc we will first need to understand the core features and basic application of streams in Dart.

As we know the basic definition of streams lets generate our own stream using the yield keyword.

using yield to generate stream’s

In the above example, we have a function getRandomNumberStream this function is present in “lib\streamGenerators.dart” (It’s better to clone the repo and take a look at the structure of the program) which output streams we have specified that by using async*. Then we have a Future.delayed() which delays our execution for the first run for 1000 ms and then 500 ms for every other subsequent execution. Then we output(yield) the value.

What yield does it basically output the data in the form of a stream, So this function is going to be our go-to for all our need for streams in this first series.

Now let me brief about all the basic functions that are available with streams.

  • .map: .map helps us to map the event that we are getting from the stream by passing them to a function. ex
StreamGenerators.getRandomNumberStream(10).map((event) => "This event --$event-- is mapped");
op:
This event --$0-- is mapped
This event --$1-- is mapped
This event --$2-- is mapped
This event --$3-- is mapped
This event --$4-- is mapped
  • .take: .take will only take the first N values and drain the rest of the values. ex
StreamGenerators.getRandomNumberStream(10).take(5)
.map((event) => event.toString() + " .take(5)");
op: 
0 .take(5)
1 .take(5)
2 .take(5)
3 .take(5)
4 .take(5)
  • .where: .where this can be helpful in case we want to filter our stream on the basis of some condition. ex:
StreamGenerators.getRandomNumberStream(20)
.where((event) =>
event % 2 !=
0)
.map((event) =>
"$event : filtering stream by eleminating element which are divisible of 2 ")
op:
1:filtering stream by eleminating element which are divisible of 2
3:filtering stream by eleminating element which are divisible of 2
5:filtering stream by eleminating element which are divisible of 2
7:filtering stream by eleminating element which are divisible of 2
9:filtering stream by eleminating element which are divisible of 2
11:filtering stream by eleminating element which are divisible of 2
13:filtering stream by eleminating element which are divisible of 2
15:filtering stream by eleminating element which are divisible of 2
17:filtering stream by eleminating element which are divisible of 2
19:filtering stream by eleminating element which are divisible of 2

There are some other methods which can be useful like expand, transform, etc. You can check out other methods at https://api.dart.dev/stable/2.10.2/dart-async/Stream-class.html.

That’s enough for basics lets tale a look at stream subscription, Stream sink, and stream function.

Stream Subscription: Stream subscription is just like handles to a stream which we can use to control the stream behavior ie. when to stop when to resume and when to cancel. You can check out the StreamSubscription example in the git repo. Let’s take a brief look at stream subscription.

StreamSubscription streamSubscription =
StreamGenerators.getRandomNumberStream(20).listen((event) { }
//accessing methods of stream
streamSubscription.pause();
streamSubscription.resume();
treamSubscription.cancel();

In the above code, we are first subscribing to a stream using the listen method. Then we are accessing the methods of stream subscription. These methods are pretty self-explanatory.

sink: are the opening of the stream where we can input data that we want our stream to consume. Let’s take a look at an example.

final _counterStateController = StreamController<int>();
StreamSink<int> get _inCounter => _counterStateController.sink;
Stream<int> get counter => _counterStateController.stream;

In the above example, we have created a StreamController and accessing its sink and stream functionality using the StreamController object. You can check more about streams and basics of how bloc implements it for its use in the below video though we will be looking at the community package for bloc like flutter_bloc in the next article.


From Our Parent Company Aeologic

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

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

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

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

See How Enriched Is Dart ?

0

Dart and its dynamism are one of the hot topics among developers these days, Since its release in 2007 to till now has been improved simultaneously. Basically, Dart is an open-source programming language that is used for different platforms like developing mobile applications, web, server, desktop, and also for Internet of things(IoT) and it is also declared “Standard ” by Ecma.

It was an introduction that everyone knows but the point of discussion is why and how dart is better (if it is) in different fields if we compare to different languages like java, javaScript, swift.


I am saying this because there are different aspects of Dart which either correlate or totally differ from other languages used for mobile application development.

Dart is an object-oriented language and gives a feel like c and if you are familiar with c or java you will be productive and proficient in the dart. However, when the dart is used in a web application it is transpiled (TRANSlate comPILER) in javascript.

The Dart installation comes with a VM as well to run the .dart files from a command-line interface. The Dart files used in Flutter apps are compiled and packaged into a binary file (.apk or .ipa) and uploaded to app stores.

Some Frequently asked questions are addressed by dart.dev itself you can visit to.

If you are trying to identify the language you use is different, better, equal, or a little less in different aspects then you need to make comparisons with others so we will see some small points and decide where Dart lies on ???

So for that, we will take a glance at the languages which are used widely for backend and frontend(not all some of them like javaScript). As you know that when react-native was introduced by Facebook the demand for javaScript went all-time high and swift has also its separate user base.

  1. Dart can be compiled both AOT and JIT which helps building apps in several ways as using JIT compilation can speed up development and AOT compilation can be used during the release process for better optimization. This technique has been used in Flutter app development
  2. Dart coding looks like most ALGOL languages such as C, java so there is not a big difference in syntax, that makes anyone able to learn easily. Things like the Flow of statements such as loops, conditions, breaks are similar.
  3. Abstraction works in a similar manner, allowing abstract classes and interfaces.
  4. if you are familiar with java you know that you need to declare everything explicitly like which type of String, int, etc but in dart you need not do that it refers according to values nature.
  5. In Dart, all data types are objects including numbers. si if you don’t initialize then the value will be counted null not Zero.
  6. All data types are objects, including numbers. So, if left uninitialized, their default value is not a 0 but is instead null.
  7. It has a new inbuilt data type called Runes, that deal with UTF-32 code points in a string. For a simple example, see emojis and similar icons.
  8. Dart also has inbuilt libraries installed in the Dart SDK, the most commonly used being:
  • dart:core for core functionality; it is imported in all dart files.
  • dart:async for asynchronous programming.
  • dart:math for mathematical functions and constants.
  • dart:convert for converting between different data representations, like JSON to UTF-8.

Reason For using in the flutter

These are some key points( mentioned above) but for an app, this is not an end, and Dart also keep surprising user by its some features like

In Dart handling of transition and animation is quite handy because it runs 60 fps, garbage collection object allocation is like javaScript. In dart preemptive scheduling and shared memory is avoidable. That makes it so much faster.

Visualization is easy with the dart in Flutter because the whole layout in one language and at the same place makes it easy to handle and responsive while in others XML or JSX needs to use a separate visual interface builder. Dart is particularly easy to learn because it has features that are familiar to users of both static and dynamic languages.

A New Approach for Programming

Using Dart in flutter is not too different however it is a static-typed OOP language, most important feature is a hot reload that helps to read and compile interfaces easily and fast. In android java and for iOS swift is being used. There is no declarative syntax akin to .xaml files in Xamarin Forms or .nib in iOS. Everything is defined by creating Dart code for widgets and the icing on the cake is Dart formatter (a dart plugin) which helps to format code on a single right-click and the code is up to date.

Conclusion

Basically, this article was not about comparison with any other language but sometimes it is required to give references for others to identify some good or bad features. Dart is no doubt best in some aspects like in compilation of code and it is still improving and there is always a scope of improvement if a community is asking for. so that was a small elaboration of few features which I know about Dart.

Thanks for reading this article if you find anything that could be improved please let me know, I would love to improve.💙

If this article has helped you a bit and found interesting please clap!👏


From Our Parent Company Aeologic

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

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

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

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

CustomScrollView & Slivers In Flutter

0

Introduction :

Appbar is basically a pre built widget inside Scaffold class which is placed as a fixed-height widget at the top of the screen. For scrollable appbar we use a SliverAppBar which embeds an appbar in a sliver for use in a CustomScrollView


Table of Contents:

:: SliverAppBar (scrollable appbar)

:: CustomScrollView

:: SliverFillRemaining class

:: SliverList


SliverAppBar Class

It is an appbar that can be integrated with a CustomScrollView. SliverAppBar is mostly used as a first child of CustomScrollView, which allows the appbar to integrate with a scrolling effect so that it can vary its height up to a certain expandable limit.

CustomScrollView:

Let’s, not bit get confused about CustomScrollView. It is basically a scroll view that creates custom scroll effects using slivers. It provides you with slivers to create various scrolling effects, such as lists and a grid with SliverList and SliverGrid.

Let’s Start: :

How to implement -:

In the body, we have defined the CustomScrollView widget which has slivers as its property which provides various scrolling effects. SliverAppBar widget is used for scrolling appbar up to a certain expandedHeight.

Here we have given an expanded height of 200 which is a given height up to which appbar will scroll down, floating effect is set as false as you do not need to set it as false as its a default value but when you want your appbar to appear while scrolling even you have not reached to the top of the list then set it as true, set pinned property as true if you do not want appbar to disappear while scrolling or set it as according to your need but remember you do not compulsory need to set is as false as is it’s the default value.

FlexibleSpaceBar class is a part of appbar that expands, collapses, and stretches. It is used to set an inner functionality of an appbar which includes title, background, and many more.

=For more Info :

FlexibleSpaceBar class
The part of a material design AppBar that expands, collapses, and stretches. Most commonly used in in the…api.flutter.dev

Till now our appbar is shown to us, but wait we are still not able to scroll down our appbar as it does not show any movement to us. But why?

Because till now, we have not provided other slivers(or any scrollable part ) to our rest filling area, so it is not able to scroll down anything.

Scrollable Part: Other slivers may include such as SliverList, SliverGrid, and SliverFillRemaining, etc.

ANow we going to fill our rest sliver zone area so that our appbar scrolls.

Lets Code: :

How to implement -:

We have filled our other sliver part with SliverFillRemaining class so that our scrolling starts performing.

SliverFillRemaining class

SliverFillRemaining class is a widget inside slivers that contain a single box child that fills the remaining space in the viewport.

Here we have used SliverFillRemaining class so that it becomes a scrollable child. We have provided some text data in column form in this class just to fill up our area so that our appbar starts scrolling.

Now our app looks like this as shown below :

Try it out, now you are able to scroll your appbar accordingly 👍

Let’s understand more :

Description :

The picture looks quite simple and its implementation is as easy as it looks…😊

The above picture contains an appbar that is scrollable and it’s a normal appbar that does not expand its size but float while scrolling.

Above we have seen that only SliverAppBar does not scroll if it is not provided with other scrollable slivers such as SliverFillRemaining, SliverList, and SliverGrid, and many more.

You have already seen how to implement SliverFillRemaining. Here you can see a list type structure in our body area, so I think you must have already guessed that we will be implementing SliverList here.

Lets Code :

Lets again start with building an appbar:-

You have already seen its explanation above, but only the basic difference is here we have not provided expandedHeight to our appbar as we do not want our appbar to expand more..!

Appbar is created till now and it will not scroll and I think we must have understood why?

As I have already explained above for scrolling it also requires scrollable slivers for something to scroll.

Lets code for it :

SliverList

SliverList is a sliver that places multiple box children in a linear array along the main axis. It is just similar to the list view.

For more info :

SliverList class
A sliver that places multiple box children in a linear array along the main axis. Each child is forced to have the…api.flutter.dev

It has one delegate property which is its required property. A delegate that supplies children for slivers. Rather than receiving their children as an explicit List, they receive their children using a SliverChildDelegate.

For more info :

SliverChildDelegate class
A delegate that supplies children for slivers. Many slivers lazily construct their box children to avoid creating more…api.flutter.dev

Inside a SliverChildListDelegate, we have created a list in which loop executes from 1 to 100, and each time its execution takes place it just creates a new widget in list form. Here we have used the ListTile widget which has child property of leading and title. It will create a 100 ListTile widget in a list form that works as a scrollable child or slivers.

So now you can see your appbar starts floating accordingly you scroll down your list and it looks the same as shown in our starting picture….👏

Hope you have enjoyed learning with us…

Refer to the below blog to build a highly custom appBar in Flutter.

Custom AppBar in Flutter
Building a beautiful AppBar using Fluttermedium.com


Thanks for reading this article ❤

Clap 👏 If this article helps you.

Feel free to post any queries or corrections you think is required…✔

From Our Parent Company Aeologic

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

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

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire 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!.

ListWheelScrollView in Flutter

0

ListView is basically a collection of non-ending or infinite data generated in form of a list.ListView is a 2-D type of list which creates data linearly.

ListView is a useful widget but sometimes leaves a normal or just a simple effect on our application.

To resolve our issue flutter also provides us with a 3-D type scrolling list type known as ListWheelScrollView.


Table of Content :

:: ListWheelScrollView class

:: Properties of ListWheelScrollView class


ListWheelScrollView class :

ListWheelScrollView class is basically a widget that is almost similar to the ListView widget but having additional 3-D effects in a list which makes it more attractive, stylish, and advanced. Normally ListView scrolls linearly in form of a list but ListWheelScrollView scrolls in form of rotation along the axis which makes it look more similar to the motion of the wheel.

When the list is assigned to zero scroll offset, the first child is aligned at the middle or selected part of the 3-D list while when the list is assigned to final scroll offset, then the last child is aligned at the middle or selected part of the 3-D list of a ListWheelScrollView.

Let’s Start

How to implement -:

Here above the code, you can see we have implemented ListWheelScrollView to generate a list in our application. The required property of this widget is itemExtent andchildren.

The itemExtent property is used to adjust the size of each child in the main axis of a list item and it should not be null and must be always a positive value. The other required property is children which are used to define the number of items added to form a list similar to ListView.

In the above code, we have given itemExtent a value of 280 which defines the size of each child. Inside,childrenwe have provided a single decorated container.

Let’s see how our app looks :

As you can see our single container inside the list is assigned in the middle because of ListWheelScrollView. The selected child is displayed in the middle or in front of your screen.

Now we will try to add multiple children inside our application and see how it looks 👀

Demo :

As you can see we have added multiple containers inside the children property of ListWheelScrollView class and it gives a more 3-D view look to our list.

As we have implemented our list in ListWheelScrollView type, now it’s time to see a more interesting property of this widget and try to implement them too.

Properties of a ListWheelScrollView :

  1. diameterRatio: It is defined as the ratio between the diameter of a cylinder and the viewport’s size in the main axis. It basically defines the diameter of a wheel or a distance from the axis of rotation.

For diameterRatio of a value set as 2, the list looks like :

For diameterRatio of a value set as 4, the list will looks like :

2. useMagnifier: this property is used to define whether to use magnifier at the centre item of our wheel or not. It takes a boolean value of either true or false.

3. magnification: it is used to define how much magnified our centre item should look. We have to provide a numeric value to it.

We have set useMagnifier property as true so it will magnify our centre item and its magnification value is 2. Let’s see how it looks.

4. offAxisFraction: this is basically a viewpoint of a wheel on how the normal wheel looks when you view it through different side angles.

When offAxisFraction is set as 1.5 which is positively valued.

When offAxisFraction is set as -1.5 which is negatively valued.

For more info visit down the link :

ListWheelScrollView class
A box in which children on a wheel can be scrolled. This widget is similar to a ListView but with the restriction that…pub.dev


Thanks for reading this article ❤

Clap 👏 If this article helps you.

Feel free to post any queries or corrections you think is required…✔

From Our Parent Company Aeologic

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

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

FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire 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

Stream Builder In Flutter

0

In this blog, we will explore the Stream Builder in a flutter. We will be using some core functions available in a flutter. We will implement a demo of the Stream Builder in your flutter applications.


Table of Contents :

Flutter

Stream Builder

Code Implementation

Code File

Conclusion


Flutter :

“ Flutter is Google’s UI toolkit that helps you build beautiful and natively combined applications for mobile, web, and desktop in a single codebase in record time

Stream Builder :

The StreamBuilder can listen to exposed streams and return widgets and capture snapshots of received stream data. The stream builder takes two arguments.

  1. A stream

2. A Builder, which can convert elements of the stream into widgets

The Stream is like a pipe. When you enter a value from one side and a listener from the other side, the listener will get that value. A stream can have multiple listeners and all those listeners can get the pipeline.puting in all will get equal value. The way you put values on the stream is by using the Stream Controller. A stream builder is a widget that can convert user-defined objects into a stream.

Demo Module :

Code Implementation

Create a new dart file calledflutter_stream_builder inside the lib folder.

final imgStream = StreamController<Image>();

First of all, Create a stream Controller.

Because we need a controller to manipulate the stream so that we create a controller with the stream property of dart.

There is a button in this screen ,on clicking ,the progress indicator will be removed and go to the next screen and will show the image one by one.

return Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
CircularProgressIndicator(
// backgroundColor:Colors.red,
),
SizedBox(
height: 100,
),
Text('Clicks Button',style:TextStyle(color:Colors.black,fontSize:15,fontWeight:FontWeight.w700),),

],
);

In this screen we have used streambuilder we have used stream and sink to trigger and share data. which is controlled with a streamcontroller for events and stream.

StreamBuilder(
stream: imgStream.stream,
builder:
(BuildContext context, AsyncSnapshot<dynamic> snapshot) {
if (!snapshot.hasData) {
return Loader();
}

if (snapshot.connectionState == ConnectionState.done) {

}

return Container(
height: 220,
width: 220,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(10)),
),
// color: snapshot.data,
child: ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(10)),
child: snapshot.data,
),
);
}),

if (imgCounter < imageList.length) {
imgStream.sink.add(imageList[imgCounter]);
} else {
imgStream.close();
}

Code File :

import 'dart:async';
import 'package:flutter/material.dart';
import 'package:flutter_stream_builder_demo/loading_widget.dart';

class FlutterStreamBuilder extends StatefulWidget {
@override
_FlutterStreamBuilderState createState() => _FlutterStreamBuilderState();
}

class _FlutterStreamBuilderState extends State<FlutterStreamBuilder> {
double _height;
double _width;

final imgStream = StreamController<Image>();

int imgCounter = -1;

final List<Image> imageList = [
Image.asset(
'assets/images/resort_1.jpg',
fit: BoxFit.cover,
),
Image.asset(
'assets/images/resort_2.jpg',
fit: BoxFit.cover,
),
Image.asset(
'assets/images/resort_3.jpg',
fit: BoxFit.cover,
),
Image.asset(
'assets/images/resort_4.jpg',
fit: BoxFit.cover,
),
];

@override
void dispose() {
imgStream.close();
super.dispose();
}

@override
Widget build(BuildContext context) {
_height = MediaQuery.of(context).size.height;
_width = MediaQuery.of(context).size.width;
return Scaffold(
body: Container(
height: _height,
width: _width,
child: Column(
mainAxisAlignment: MainAxisAlignment.spaceAround,
crossAxisAlignment: CrossAxisAlignment.center,
children: [
StreamBuilder(
stream: imgStream.stream,
builder:
(BuildContext context, AsyncSnapshot<dynamic> snapshot) {
if (!snapshot.hasData) {
return Loader();
}

if (snapshot.connectionState == ConnectionState.done) {}

return Container(
height: 220,
width: 220,
decoration: BoxDecoration(
borderRadius: BorderRadius.all(Radius.circular(10)),
),
// color: snapshot.data,
child: ClipRRect(
borderRadius: BorderRadius.all(Radius.circular(10)),
child: snapshot.data,
),
);
}),
RaisedButton(
shape: new RoundedRectangleBorder(
borderRadius: new BorderRadius.circular(30.0),
),
onPressed: () {
// colorStream.sink.add(Colors.blue);

imgCounter++;

if (imgCounter < imageList.length) {
imgStream.sink.add(imageList[imgCounter]);
} else {
imgStream.close();
}
},
color: Colors.red,
textColor: Colors.white,
child: Text(" Click Me ".toUpperCase(),
style: TextStyle(
fontSize: 14,
fontWeight: FontWeight.w600,
letterSpacing: 1)),
),
],
),
),
);
}
}

Conclusion :

In this article, I have explained a Stream Builder demo, you can modify and experiment according to your own, this little introduction was from the Stream Builder our side.

I hope this blog helps will provide you with sufficient information in Trying up the Stream Builder in your flutter project. 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 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

Obfuscating The Flutter App

0

In-app development, it is important to manage its performance. Performance covers different aspects like speed and responsiveness and it depends on things like app size and rendering performance.

if we talk about issues related to performance there are two types of issues some are space-related issues and some are time-related issues.


Time-related issues occur when the app starts consuming too much time on any tasks or when it forces the device to run at a faster pace.

Here we are going to address the problem of app size, as you well know when we build our app it consists of too many things and in the end, we get an app bigger in size so here we are going to learn how do we get rid of this issue.

App Size

App size is an issue that can bother anyone whether they are developers or users. as you know that the APK, app bundle, or IPA all of them contain everything like code and assets and run itself with them and if it’s size is heavy then it may create trouble because if it is large in size it will take more space and it may break the limit of useful features like Android instant apps.

when you launch your app using the IDE button or by running flutter run the command, it generates a debug build and large in size but it allows to hot reload and source-level debugging.

Now we would see how we check and estimate the size of a flutter app…

The release APK generally we create usingflutter build apk or flutter build ios provide the uploaded package to the play store or app store but they do not represent the end user’s download size, the app store generally reprocesses and split the uploaded package to in order to make suitable for the downloader’s device by filtering the things like native’s library, phone’s DPI.

Reducing the app size

Size reduction becomes one of the vital processes when it comes to making your app available for users.

Starting in Flutter version 3.22 and DevTools version 3.4, a size analysis tool is included to help developers understand the breakdown of the release build of their application.

The size analysis tool is invoked by passing the --analyze-size flag when building:

  • flutter build apk --analyze-size
  • flutter build appbundle --analyze-size
  • flutter build ios --analyze-size
  • flutter build linux --analyze-size
  • flutter build macos --analyze-size
  • flutter build windows --analyze-size

In the case of android APK or bundle, you also need to mention the target platform and one of the android arm so the commands will be like

flutter build apk --target-platform android-arm --analyze-size
flutter build apk --target-platform android-arm64 --analyze-size
flutter build apk --target-platform android-x64 --analyze-size
flutter build appbundle --target-platform android-arm --analyze-size
flutter build appbundle --target-platform android-arm64 --analyze-size
flutter build appbundle --target-platform android-x64 --analyze-size

and the result will be like

and build will be different in two ways

  1. The tool compiles Dart in a way that records code size usage of Dart packages.
  2. The tool displays a high-level summary of the size breakdown in the terminal and leaves a *-code-size-analysis_*.json file for more detailed analysis in DevTools.

As you can see in the picture, how much space every item is acquiring, and if you want any kind of deep analysis you can use Devtools.

If you don’t have any idea how to use dev tools you can see my blog here.

Now let’s focus on how to reduce the size?

When you are building the release version of an app you need to run this command --split-debug-info this will automatically reduce the size of the app. However, you can see Obfuscating the dart code.

Code obfuscation is the process of modifying an app’s binary to make it harder for humans to understand. Obfuscation hides function and class names in your compiled Dart code, making it difficult for an attacker to reverse engineer your proprietary app.

So if you want to obfuscate your app then you need to check version for different platforms

For android/iOS: you need a minimum of Flutter version 1.16.2 to do this, To obfuscate an app built against an earlier version of Flutter, use the process mentioned above.

For macOS: macOS (in alpha as of Flutter 1.13), supports obfuscation as of Flutter 1.16.2.

Linux/Windows: Not Available

web: Not Available

Flutter’s code obfuscation, when supported, works only on a release build.

Note: You need to run flutter upgrde and the latest version will be available.

You can also use these steps in order to reduce the app size

  • Remove unused resources
  • Minimize resource imported from libraries
  • Compress PNG and JPEG files

Obfuscation of an app:

There is a simple procedure for obfuscation of the flutter app, you only need to run the build command for the release version using the --obfuscate flag combined with the --split-debug-info flag.

This --split-debug-info refers to the location or directory where flutter outputs the debug files. This command generates a symbol map. The apk, appbundle, iosand ios-framework targets are currently supported. (macos and aar are supported on the master and dev channels.) for example

flutter build apk --obfuscate --split-debug-info=/<project-name>/<directory>

Once you’ve obfuscated your binary, save the symbols file. You need this if you later want to de-obfuscate a stack trace.

Once you’ve obfuscated your binary, save the symbols file. You need this if you later want to de-obfuscate a stack trace.

For the detail information on these commands, you can run flutter build apk -h and if you are not getting any info then you need to check your flutter version and if it does not support then run the flutter upgrade.

Reading the Obfuscating stack trace

To debug a stack trace created by an obfuscated app, use the following steps to make it human-readable:

  1. Find the matching symbols file. For example, a crash from an Android arm64 device would need app.android-arm64.symbols.
  2. Provide both the stack trace (stored in a file) and the symbols file to the flutter symbolize command. For example:
flutter symbolize -i <stack trace file> -d /out/android/app.android-arm64.symbols

For more information on the symbolize command, run flutter symbolize -h.

Conclusion

After doing all the pieces of stuff explained in the article finally we have reduced the total app size which helps users as well as developers to work faster with there respective work but that was only one issue which has been addressed in order to make apps responsive and faster another issue related to rendering will be addressed in an upcoming blog.

Thanks for reading this article if you find anything that could be improved please let me know, I would love to improve.💙

If this article has helped you a bit and found interesting please clap!👏


From Our Parent Company Aeologic

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

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

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

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

In-App Purchases In Flutter

0

Hello everyone, Today we will take a look at flutter’s latest package for handling in-app purchases. So, while I will be covering most of what to do to get in-app purchases working, I highly recommend checking out the official documentation of the package provided by the flutter team — https://pub.dev/packages/in_app_purchase

in_app_purchase | Flutter Package
A Flutter plugin for in-app purchases. Exposes APIs for making in-app purchases through the App Store (on iOS) and…pub.dev

So why in app purchases?

Well these in app purchases are required when we are selling digital content so that means things like stripe api wont work here.

NOTE : THIS PACKAGE IS IN BETA SO THERE MAY BE SOME ERRORS , I WILL MAKE SURE TO UPDATE THE ARTICLE AS SOON AS IT COMES OUT OF BETA VERSION

Now that that’s out of the way we will see the different types of products you can purchases through the use of this package.

  • Consumable
  • Non-Consumable
  • Subscription

In this particular article we will only talk about the first one that is Consumable type of purchases.

These types of purchases are the ones user can make again and again like some sort of currency in a game for example primogems in genshin impact or Iris in Danmemo or gems in Clash of Clans etc,

These purchases are called consumables cause user tend to consume them over time and once depleted they want to buy it again.

Fun Fact : Fate/Grand Order game made about $4 billion as of January 31, 2020 by selling their in-game currency called saint quartz

They were able to achieve this by making their app highly fun and addicting which got people to spend more to get the characters they want. Now that we covered what are consumable types of purchases lets move on to their implementation

First we need to add the package in pubspec.ymal file

in_app_purchase: ^latest version

There are a few steps that need to be completed before we can use it as we like, see here.

After we are done with the native steps and have a signed application on google play store and app store and have products added to them, we will move on to the code

In the void main of your app add this —

void main() {
// without this we will get an error when we try to access any instance
InAppPurchaseConnection.enablePendingPurchases();

runApp(MyApp());

}

Without this we would not be able to access play store or the app store, so it is a must.

After you have added this line in void main we will move onto our code in the initState of the app

initialize() async {
connectionAvailable = await _connection.isAvailable();

if (connectionAvailable) {
await getListOfproductsFromOurStore();
await getListOfPastPurchasesMadebyUser();

_verifyPurchases();

_subscription = _connection.purchaseUpdatedStream.listen((info) {
setState(() {
print('user is making a new purchase');
purchases.addAll(info);
});
});
}
}

So in the initState, of my app I called a method called to initialize that will check if the connection is established or not, if it is available we will get a list of our products from the play store/ app store and get a list of past purchases made by the user, then we call a method to verify() to verify those purchases

then we have a variable of type StreamSubscription<List<PurchaseDetail>>

StreamSubscription<List<PurchaseDetails>> _subscription;
final InAppPurchaseConnection _connection = InAppPurchaseConnection.instance;
bool isAvailable = true;
List<ProductDetails> productDetails = [];
List<PurchaseDetails> purchasesDetails = [];
StreamSubscription subscription;
int gems = 0;
final String testID = 'test_gems';

And we provide it value inside the initialization function like so

_subscription = _connection.purchaseUpdatedStream.listen((info) {
setState(() {
print('!!!!!!!user is making a new purchase!!!!!!!!');
purchasesDetails.addAll(info);
});
});

what this does it, it subscribes to any incoming purchases from either play store or app store.

Now we will work on the getting the list of products from our store which will be done by this method we have already called in initialize

Future<void> getListOfproductsFromOurStore() async {
Set<String> ids = Set.from([testID]);
ProductDetailsResponse response = await _connection.queryProductDetails(
ids);

setState(() {
productDetails = response.productDetails;
});
}

We have done a basic query where we get all the products whose ids match the one we have provided

You can also do this for multiple ids

  • const Set<String> _kIds = {'product1', 'product2'};
  • final ProductDetailsResponse response = await InAppPurchaseConnection.instance.queryProductDetails(_kIds);

So after we get the response we set them in our productDetails, now we have the list of all the products we have available on our play store and app store

Now we will try to load our past purchases by using another method defined in initialize() that is

Future<void> getListOfPastPurchasesMadebyUser() async {
QueryPurchaseDetailsResponse response = await _connection.queryPastPurchases();

for (PurchaseDetails purchaseDetails in response.pastPurchases) {
if (Platform.isIOS) {
_connection.completePurchase(purchaseDetails);
}


setState(() {
purchasesDetails = response.pastPurchases;
});
}
}

Here we have simply made a query to get all the past purchases made by the user and then used a for in loop to sort through them and then set the value of purchasesDetails equal to the response.pastPuchases we got from the query

Now to finally do the purchase we will use this function

buy(ProductDetails pd) {
final PurchaseParam purchaseParam = PurchaseParam(productDetails: pd);
_connection.buyConsumable(purchaseParam: purchaseParam);
}

So we create a PuchaseParam type variable and set it same value as the value we will get from a particular value in a list of productDetails list

After that we will use .buyConsumable method which takes a parameter of purchaseParam and then we pass the variable we created there.

That is all we need to do in order to complete an in-app purchase.


From Our Parent Company Aeologic

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

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

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

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

Related: Streamlining Payments In Flutter

Animated list In Flutter

0

In this blog, I am telling Implement the animated list. In this app, we will present the normal list item how to display Listview using Flutter Animated List widget. It will not contain any kind of package in it. We will implement a demo of the Animated list in your flutter applications.


Table of Contents :

Flutter

Animated List

Code Implementation

Code File

Conclusion


Flutter :

“ Flutter is Google’s UI toolkit that helps you build beautiful and natively combined applications for mobile, web, and desktop in a single codebase in record time

Animated list:

The Animated list is like a list.you can update and delete the list in this list. But with the normal list view application, the user will not know about the update. So we can add and remove any list. in this, the user will know about the update in the animated list widget we can change different types of animation transitions. And for flutter development, we can get it easily by using animated list class.

Demo Module :

Code Implementation :

Create a new dart file calledanimated_list inside the lib folder.

final key = GlobalKey<AnimatedListState>();

We will use this global key because we can change the background in the app without losing the state of the widget. if you want to show the same widget on two different screens, then the first scenario can be an example.

AnimatedList(
key: key,
initialItemCount: animatedList.length,
itemBuilder: (context, index, animation) =>
buildItem(animatedList[index], index, animation),
),

Now we have used the animated list widget in this screen. the item builder function is called for all indexes for the list view. Like you can build all the items. in the animated list, you find an object that starts the item automatically and that you can use to animate the item. It can contain any animation

void removeItem(int index) {
final item = animatedList.removeAt(index);

key.currentState.removeItem(
index,
(context, animation) => buildItem(item, index, animation),
);
}

Now we will create a method named removeItem(). In which we will tell that the item is being removed from the animated list. To show the widget, we will remove the list item with the help of the builder.

void insertItem(int index, AnimatedListModel item) {
animatedList.insert(index, item);
key.currentState.insertItem(index);
}

We have created a method named insert item which tells the animated list that a new item has been added to the list. to create a new item which is used by the animated list.

Code File :

import 'package:flutter/material.dart';
import 'package:flutter_animated_list_demo/Constants/Constants.dart';
import 'package:flutter_animated_list_demo/list_item_widget.dart';
import 'package:flutter_animated_list_demo/model/animated_list_model.dart';
import 'package:flutter_animated_list_demo/resources/themes/appthemes.dart';

class AnimatedListDemo extends StatefulWidget {
@override
_AnimatedListDemoState createState() => _AnimatedListDemoState();
}

class _AnimatedListDemoState extends State<AnimatedListDemo> {
final key = GlobalKey<AnimatedListState>();
static final List<AnimatedListModel> animatedList = [
AnimatedListModel(
title: 'Julia',
img: 'assets/images/rating_two.png',
),
AnimatedListModel(
title: 'Sam',
img: 'assets/images/rating_four.png',
),
AnimatedListModel(
title: 'Anthony',
img: 'assets/images/rating_one.png',
),
AnimatedListModel(
title: 'Julia',
img: 'assets/images/rating_two.png',
),
];

@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.grey[100],
appBar: AppBar(
title: Text('Animated List'),
centerTitle: true,
),
body: Column(
children: [
Expanded(
child: AnimatedList(
key: key,
initialItemCount: animatedList.length,
itemBuilder: (context, index, animation) =>
buildItem(animatedList[index], index, animation),
),
),
],
),
floatingActionButton: FloatingActionButton(
onPressed: () {
insertItem(0, animatedList.first);
},
child: Icon(
Icons.add,
color: Colors.white,
),
backgroundColor: Colors.pink[300],
),
);
}

Widget buildItem(item, int index, Animation<double> animation) =>
ListItemWidget(
item: item,
animation: animation,
onClicked: () => removeItem(index),
);

void insertItem(int index, AnimatedListModel item) {
animatedList.insert(index, item);
key.currentState.insertItem(index);
}

void removeItem(int index) {
final item = animatedList.removeAt(index);

key.currentState.removeItem(
index,
(context, animation) => buildItem(item, index, animation),
);
}
}

Conclusion :

In this article, I have explained an Animated List demo, you can modify and experiment according to your own, this little introduction was from the Animated list our side.

I hope this blog helps will provide you with sufficient information in Trying up the Animated list in your flutter project. 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 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!.