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
.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
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.
//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.
Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.
Feel free to connect with us: And read more articles fromFlutterDevs.com.
FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.
Wewelcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.
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.
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
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.
Abstraction works in a similar manner, allowing abstract classes and interfaces.
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.
In Dart, all data types are objects including numbers. si if you don’t initialize then the value will be counted null not Zero.
All data types are objects, including numbers. So, if left uninitialized, their default value is not a 0 but is instead null.
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.
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!👏
Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.
Feel free to connect with us: And read more articles fromFlutterDevs.com.
FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.
Wewelcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.
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 SliverAppBarwhich embeds an appbar in a sliver for use in a CustomScrollView
It is an appbar that can be integrated with a CustomScrollView. SliverAppBar is mostly used as afirst childof 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 andSliverGrid.
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.
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.
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.
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.
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.
Wewelcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.
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.
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 itemExtentandchildren.
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 :
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.
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.
Wewelcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.
In this 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 theStream Builder in your flutter applications.
“ 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.
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.
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.
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.
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.
Wewelcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences
In-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
The tool compiles Dart in a way that records code size usage of Dart packages.
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
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:
Find the matching symbols file. For example, a crash from an Android arm64 device would need app.android-arm64.symbols.
Provide both the stack trace (stored in a file) and the symbols file to the flutter symbolize command. For example:
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!👏
Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.
Feel free to connect with us: And read more articles fromFlutterDevs.com.
FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.
Wewelcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.
Hello everyone, Today we 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
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
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
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
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
Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.
Feel free to connect with us: And read more articles fromFlutterDevs.com.
FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.
Wewelcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.
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.
“ 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.
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);
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.
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.
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.
Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.Feel free to connect with us: And read more articles fromFlutterDevs.com.
FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, Twitter, and LinkedIn for any flutter related queries.
Wewelcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!.
Animations are a fundamental piece of causing the UI of a mobile application to feel regular and smooth to the client. Smooth transitions and intelligent components make an application charming to utilize. Exacerbate the application through and through. Consequently, learning the basics of animations in any structure is a fundamental stage toward delivering a prevalent user experience.
This article will be Explore Shake Effect In Flutter.We will see how to implement a demo program. We are going to learn about how we can shake effect in your flutter applications.
The below demo video shows how to implement a Shake Effect in a flutter. It shows how the Shake Effect will work in your flutter applications. It shows our widgets that shake when the user presses the button. Then, the widget will be shaken with some errors. It will be shown on your device.
Demo Module :
How to implement code in dart file :
You need to implement it in your code respectively:
Create a new dart file called animation_controller.dart inside the lib folder.
We will initially be going to make an animation controller class. We will require AnimationContoller to accomplish our desired impact, so we will make a different abstract state class.
import 'package:flutter/material.dart';
abstract class AnimationControllerState<T extends StatefulWidget> extends State<T> with SingleTickerProviderStateMixin { AnimationControllerState(this.animationDuration);
final Duration animationDuration; late final animationController = AnimationController(vsync: this, duration: animationDuration);
We will add the final Duration and the final animationController is equal to the AnimationController(vsync: this, duration: animationDuration). Also add dispose() method. In this method, we will add animationController.dispose().
Create a new dart file called custom_shake_widget.dart inside the lib folder.
We should characterize a StatefulWidget as a subclass that takes a child widget alongside a few adaptable properties. This widget will be mindful to shake our different widgets.
In this class, we will add a status audience to reset our AnimationController. This is significant as we need to show this error at various times and on the off chance that we don’t reset our controller then we can not see this impact once more.
In the build method, we will utilize the animation with AnimatedBuilder and Transform. translate. We will return an AnimatedBuilder() technique. In this technique, we will add animationController and child. In a child, we will add the widget. child. Likewise, we will add a builder method.
In the class, we will likewise add the shake() strategy. This strategy will be liable for the shaken impact. This strategy ought to be public. We will add inside an animationController.forward().
void shake() { animationController.forward(); }
Create a new dart file called main.dart inside the lib folder.
In the main. dart file, we will create a HomeScreen class. In this class, we will utilize GlobalKey to control the shaken impact (or to shake our widgets). Flutter gives GlobalKey that we can use as per our requirements regardless of the state. For this situation, we will require the state so we can start the shake during any taps. We will add two TextEditingControllers and three GlobalKeys.
late GlobalKey<FormState> _formKey; late GlobalKey<CustomShakeWidgetState> _emailIDState; late GlobalKey<CustomShakeWidgetState> _passwordState; late TextEditingController _emailEditingController; late TextEditingController _passwordEditingController;
We will create an initState() method. In this method, we will add _formKey is equal to the GlobalKey(), _emailIDState is equal to the GlobalKey(), _passwordState is equal to the GlobalKey(), _emailEditingController is equal to the TextEditingController(), and _passwordEditingController is equal to the TextEditingController().
In the body, we will create two TextformField widgets. In this widgets will wrap to CustomShakeWidget() method. In this method, we will add key, duration, shakeCount, and shakeOffset.
Now, we will create an ElevatedButton(). In this button, we will add style and the onPressed() function. Also, we will add a child. In a child, we will add the Text “Log In”. When the user presses the button then, our widget will shake with show some errors.
class _HomeScreenState extends State<HomeScreen> { late GlobalKey<FormState> _formKey; late GlobalKey<CustomShakeWidgetState> _emailIDState; late GlobalKey<CustomShakeWidgetState> _passwordState; late TextEditingController _emailEditingController; late TextEditingController _passwordEditingController;
In the article, I have explained the Shake Effect basic structure in a flutter; you can modify this code according to your choice. This was a small introduction to Shake Effect On User Interaction from my side, and it’s working using Flutter.
I hope this blog will provide you with sufficient information on Trying the Shake Effect in your flutter projects. We will show you what the Introduction is. Make a demo program for working Shake Effect using the custom widget 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.
Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.
Feel free to connect with us: And read more articles fromFlutterDevs.com.
FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! For any flutter-related queries, you can connect with us on Facebook, GitHub, Twitter, and LinkedIn.
Wewelcome feedback and hope that you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.
Firebase is an amazing platform developed by Google to connect mobile and web applications and help developers to improve, build, and grow their apps. Firebase provides us a variety of products Authentication, Realtime Database, Cloud Firestore, Cloud Storage, Cloud Functions, Firebase Hosting, ML Kit. Firebase is highly effective and easy to use.
Firebase cloud firestore is a flexible and scalable database. It offers offline availability of data across your client’s apps and keeps data in-sync across clients apps through realtime listeners.
In this blog, we shall discuss how to work with cloud firestore subcollections:
To work with firebase cloud firestore in flutter you need to learn about basic crud operation i.e. uploading data, deleting data, editing data, fetching data.
Let’s understand subcollection through an example, take an example of a shopping application, in this app, there are two people 1st the user that will place the order and the 2nd wander that will accept the user’s orders. For each user, the wander needs to keep a record of every user’s order. So to keep the data in a sequential manner we can create a subcollection in the following manner.
***Subcollection example***
In the above image, you can easily analyze the user’s order in an easier and precise manner. So to create this type of collection we need to specify the documentId .
Why the documentIdis important?
Assigning a specific documentId is very important if you are building two different applications one for the user and the other for a wander. To fetch all the orders with the user’s details we need to get all the documentIdof all orders placed by different users inside our wanders application. So to get that documentIdwe need to fetch it from the userscollection that I have created.
Let me explain to you the whole cycle of getting that documentId :
At the time of user authentication auserId is generated by the firebase, we will use this userId and upload it along with user information on cloud firestore inside a userscollection.
Now we can access the subcollection that we have created named orderand we use this id to get all the users and orders.
***Uploading user data on cloud firestore inside users collection******Uploading user orders inside orders collection using userId as document id******User order documents inside the user_orders sub collection***
Connecting app to your firebase project:
If you are new to firebase then you can follow the steps that I have mentioned in my crud operation blog to connect your apps to Firebase, you can add more then one app to your firebase project:
As we have discussed above, we need a users collection that will store the userId and other users information. We will create this collection when the user signs up.
Here usersis a collection that contains a document whose id is userId i.e. userCredential.user.uid .
Creating a sub-collection:
ordersis a collection that contains a document whose id is the userId that we can easily get through FirebaseAuth instance using currentUser.
User user = FirebaseAuth.instance.currentUser; , inside this document, we will create another collection user_orders . user_ordersis our sub-collection.
await FirebaseFirestore .instance .collection('orders') .doc(user.uid) .collection( "user_orders") .add({ //add your data that you want to upload });
Fetching a sub-collection:
To fetch orderssubcollection we will need the documentId, so to get the documentId we need to fetch the userscollection to get the userId .
Trusted across industries like manufacturing, healthcare, logistics, BFSI, and smart cities, Aeologic combines innovation with deep industry expertise to deliver future-ready solutions.
Feel free to connect with us: And read more articles fromFlutterDevs.com
FlutterDevs team of Flutter developers to build high-quality and functionally-rich apps. Hire a flutter developer for your cross-platform Flutter mobile app project on an hourly or full-time basis as per your requirement! You can connect with us on Facebook, GitHub, and Twitter for any flutter related queries.
We welcome feedback and hope that you share what you’re working on using #Flutter. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences!