Google search engine
Home Blog Page 78

Explore Futures In Flutter

0

Long-running errands or asynchronous activities are normal in portable applications. For instance, these tasks can be getting information over a network, keeping in touch with the database, perusing information from a document, and so forth

To perform such tasks in Flutter/Dart, we for the most part utilize a Future class and the keywords async and await. A Future class permits you to run work asynchronously to let loose whatever other threads ought not to be obstructed. Like the UI thread.

In this blog, we will Explore Futures In Flutter. We will see how to use the future in your flutter applications.

Table Of Contents::

What is the Future?

How to Using a Future

Error Handling

How to Managing Multiple Futures at Once

Timeouts

Conclusion



What is the Future?:

A Future addresses a computation that doesn’t finish right away. Though a typical function returns the outcome, an asynchronous function returns a Future, which will ultimately contain the outcome. The Future will reveal to you when the outcome is prepared.

So, a Future can be in one of three states:

  • > Uncompleted: The output is closed.
  • > Completed with value: The output is open, and data is ready.
  • > Completed with an error: The output is open, but something went wrong.

A Future is characterized precisely like a function in Dart, yet rather than Void, you utilize Future. If you need to return a value from Future, you pass it a Type.

Future myFutureAsVoid() {}
Future myFutureAsType() {}

Thus, in the accompanying code model, fetchUserOrder() returns a Future that finishes subsequent to printing to the console. Since it doesn’t return a usable value, fetchUserOrder() has the sort Future.

Future fetchUserOrder() {
return Future.delayed(Duration(seconds: 2), () => 
print('DATA'));
}
void main() {
fetchUserOrder();
print('Fetching user order..');
}

As should be obvious, even though fetchUserOrder() executes before the print() call, the console will show the yield “Fetching user order “ before the yield from fetchUserOrder(): “DATA”. This is because fetchUserOrder() delays before it prints “DATA”.

How to Using a Future:

There are two different ways to execute a Future and utilize the value it returns. If it returns any whatsoever. The most well-known way is to await on the Future to return. For everything to fall into work, your function that is calling the code must be checked async.

Future getProductCostForUser() async {
var user = await getUser();
var order = await getOrder(user.uid);
var product = await getProduct(order.productId);
return product.totalCost;
}
main() async {
var cost = await getProductCostForUser();
print(cost);
}

When an async function summons awaits, it is changed over into a Future and put into the execution line. At the point when the awaited Future is finished, the calling capacity is set apart as prepared for execution and it will be continued at some later point because the value of what was value is contained inside a Future object. The significant contrast is that no Threads should be stopped in this model.

In other words, async-await is only a decisive method of characterizing asynchronous functions and utilizing their outcomes into the future and it gives syntactic sugar that assists you with composing clean code including Futures. Here’s a memorable thing! If awaits will be utilized, we need to ensure that both the caller function and any capacities we call inside that function utilize the async modifier.

In some cases, you would prefer not to transform the function into a Future or imprint it async, so the alternate method to deal with a Future is by utilizing the .then function. It takes in a capacity that will be known as the value kind of your Future. It’s like a Promise in JavaScript without the determination, reject expresses.

void main() {
Future.delayed(
const Duration(seconds: 3),
() => 100,
).then((value) {
print('The value is $value.'); // Prints later, after 3 seconds.
});
print('Waiting for a value...'); // Prints first.
}

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

Waiting for a value... (3 seconds pass until callback executes)
The value is 100.

Error Handling:

Prospects have their own specific manner of taking care of handling errors. In the .then call and passing in your callback, you can likewise pass in a capacity to onError that will be called with the mistake got back from your Future.

FlatButton(
child: Text('Run My Future'),
onPressed: () {
runFuture();
},
)
// Future
Future myFutureAsType() async {
await Future.delayed(Duration(seconds: 1));
return Future.error('Error from return!');
}
// Function to call future
void runFuture() {
myFutureAsType().then((value) {
// Run extra code here
}, onError: (error) {
print(error);
});
}

If you run the code above, you’ll see the ‘Error from return!’ message printed out following 1 second. If you need to expressly deal with and get errors from the Future, you can likewise utilize a devoted capacity called catchError.

void runFuture() {
myFutureAsType().then((value) {
// Run extra code here
})
.catchError( (error) {
print(error);
});
}

When dealing with a mistake in your Future you don’t have to consistently get back to the Future. error. All things considered, you can likewise throw an exception and it’ll show up at the same .catchError or onError callback.

Future myFutureAsType() async {
await Future.delayed(Duration(seconds: 1));
throw Exception('Error from Exception');
}

You can also mix await and .catchError. You can await a Future and use the .catchError call instead of wrapping it. This way, the value returned is null, but you can handle the error as well without wrapping it in try/catch.

You can likewise blend await and .catchError. You can await a Future and use the .catchError call as opposed to wrapping it. Along these lines, the value returned is invalid, yet you can deal with the blunder too without enveloping it by try/catch.

Future runMyFuture() async {
var value = await myFutureAsType()
.catchError((error) {
print(error);
});
}

How to Managing Multiple Futures at Once:

We should take a model where you have a screen where you can tap to download different things out of a list. You need to wait that this load of Futures will be finished before you proceed with your code. Future has a handy .wait call. This call permits you to give a list of Futures to it and it will run every one of them. At the point when the last one is finished, it will return context to your present Future.


FlatButton(
child: Text('Run Future'),
onPressed: () async {
await runMultipleFutures();
},
)
// Future to run
Future myFutureAsType(int id, int duration) async {
await Future.delayed(Duration(seconds: duration));
print('Delay complete for Future $id');
return true;
}
// Running multiple futures
Future runMultipleFutures() async { // Create list of multiple futures
var futures = List();
for(int i = 0; i < 5; i++) {
futures.add(myFutureAsType(i, Random(i).nextInt(5)));
}
   await Future.wait(futures);
// We're done with all futures execution
print('All the futures has completed');
}

If you tap the flat button above, we will start five Futures altogether and wait that every one of them will finish. You should see an outcome as the one shown underneath. It’s utilizing a random generator, so you’ll see various orders of the IDs.

I/flutter (12116): Delay complete for Future 2
I/flutter (12116): Delay complete for Future 3
I/flutter (12116): Delay complete for Future 0
I/flutter (12116): Delay complete for Future 4
I/flutter (12116): Delay complete for Future 1
I/flutter (12116): All the futures has completed

Timeouts:

In some cases, we don’t realize precisely how long a Future will run. It is a cycle that the client needs to unequivocally wait for, for example, there’s a loading indicator on the screen, so you presumably don’t need it to run for a really long time. On the off chance that you have something like this, you can break a Future utilizing the timeout call.

Future myFutureAsType(int id, int duration) async {
await Future.delayed(Duration(seconds: duration));
print('Delay complete for Future $id');
return true;
}
Future runTimeout() async {
await myFutureAsType(0, 10)
.timeout(Duration(seconds: 2), onTimeout: (){
print('0 timed out');
return false;
});
}

On the off chance that you run the code above, you’ll see 0 timed out and you’ll never see Delay total for Future 0. You can add extra rationale into the onTimeout callback.

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying up the Explore Futures in your flutter projectsWe will show you What are the Future is?. It covers the fundamentals of what you’d need to deal with Futures in your code. There’s additionally the function .asStream that you can on utilizing a Future to return the outcomes into a stream. On the off chance that you have a codebase overwhelmed by streams, you can utilize this and consolidate it with your different streams effectively whenever required. So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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

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


Exploring Inheritance and Composition in Dart & Flutter

0

UI structures actually utilize inheritance as a key tool to stay away from code excess, and the Flutter system is no exemption. All things being equal, when you compose Dart code that isn’t straightforwardly expanding the UI system, it is ideal to keep your inheritance chains shallow and favor piece when it bodes well.

There is a pattern in software development away from the profound, branching class trees mainstream with object-arranged languages. Some accept more current functional ideal models ought to altogether supplant OOP in the software plan. This leaves numerous with the possibility that inheritance is not placed in software development anymore, or that its utilization ought to be rigorously restricted.

In this blog, we will be Exploring Inheritance and Composition in Dart & Flutter. We will take a look at how inheritance and composition patterns will work with dart and flutter in your flutter applications.

Table Of Contents::

What is Inheritance in Flutter?

Types of Inheritance

Inheritance In Data Models

What is Composition in Flutter?

Use of Composition child pattern in Flutter

Composition In Data Models

Conclusion


What is Inheritance in Flutter?:

Inheritance is the capacity of a class to inherit properties and strategies from a superclass and the’s superclass, etc. It is exemplified in Dart by the @override metatag. With it, a subclass’s execution of inherited conduct can be particular to be proper to its more explicit subtype. It permits extending out a class to a particular adaptation of that class. As said before all classes acquire from the Object type, just by pronouncing a class, we expand the Object type. Dart permits a single direct legacy and has uncommon help for mixins, which can be utilized to extend class functionalities without direct inheritance, simulating various inheritances, and reusing code.

Mixins are a method of reusing a class code in numerous class hierarchies. To utilize a mixin, utilize the with a keyword followed by at least one mixin name. To indicate that lone particular sorts can utilize the mixin — for the model, so your mixin can summon a strategy that it doesn’t define — use on to determine the necessary superclass.

The Flutter UI structure, all written in open-source Dart, is brimming with instances of inheritance. Indeed, a large number of the standard examples in building Flutter applications depend on these ideas:

class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Container();
}
}

This is the most straightforward illustration of a custom widget in Flutter. It utilizes theextends keyword to demonstrate that the class ought to inherit properties and strategies from StatelessWidget, which itself inherits from the Widget class. This is significant because each Flutter widget has a build() technique accessible that profits an occurrence of Widget.

Everything in Dart extends Object, so boundaries composed as Object will acknowledge any value. Inheritance is at the actual center of the language. Container extends StatelessWidget which expands Widget, so build()can return a Container object, and containers can be remembered for List assortments composed as Widget.

class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Container(),
Container(),
Column(),
],
);
}
}

Column widgets acknowledge a children boundary composed as a List of Widget objects. Counting <Widget> before the rundown exacting shows that you need just widgets in the list. The Dart code analyzer will grumble if a non-widgets is incorporated. Both Container and Column are widgets, so this is substantial code.

Types of Inheritance:

There are four types of Inheritance are:

  • > Single Inheritance: In this inheritance when a class inherits a single parent class then this inheritance happens.
  • > Multiple Inheritance: In this inheritance when a class inherits more than one parent class then this inheritance happens.

Note: Dart doesn’t support Multiple Inheritance.

  • > Multi-Level Inheritance: In this inheritance when a class inherits another child class then this inheritance happens.
  • > Hierarchical Inheritance: In this inheritance, more than one class has the same parent class.

Inheritance In Data Models:

Similarly, as Flutter utilizes center OOP standards to show the UI, you can utilize them to display your information. How about we make information develop to hold the substance of a message and another that incorporates an image with the content.

class Message {
String text;
  Message({@required this.text});
}
class ImgMessage extends Message {
String imageUrl;
  ImgMessage({@required String text, @required this.imageUrl}) :
super(text: text);
}

It is anything but a ton of code, however, there’s a great deal going on in this model. To start with, we make a Message class to contain something like a text message. A message isn’t anything without its content, so we ensure passing in the content is required, and we utilize a named boundary for additional lucidity.

The ImgMessage class expands Message, which implies it acquires the text property. Constructors in Dart are not inherited, so we give ImgMessage its own constructor, and it needs to acknowledge two values named text and imageUrl. Since the text is actually important for Message, not ImgMessage, we can’t utilize programmed instatement for it, and we need to indicate its sort (String) so Dart doesn’t acknowledge only any kind of significant worth there.

Following the ImageMessage constructor’s boundary list, we add a colon, after which Dart will expect an initializer list. This is a comma-delimited list of initializers for our objects, regularly used to introduce properties before any constructor body code runs, which is needed with final properties. Here, we utilize the super keyword to consider the constructor of the ImageMessage class’ superclass, which is Message. The Message constructor will deal with relegating the content contention to the content example variable.

To elaborate how inheritance can profit us, we’ll need a list of instance messages to work with:

final messages = <Message>[
Message(text: "Message 1"),
Message(text: "Message 2"),
ImgMessage(
text: "Message 3",
imageUrl: "https://flutter.com/image1.jpg",
),
];

Even though composed of a collection of Message objects utilizing Dart generics, messages will acknowledge any item with the Message class in its parentage.

Presently we can make a widget to show the list of messages, and it will actually want to deal with one or the other kind of message while dismissing or anything:

class MessageList extends StatelessWidget {
final List<Message> messages;
  const MessageList({Key key, @required this.messages}) :
super(key: key);
  @override
Widget build(BuildContext context) {
return Column(
children: messages.map((Message msg) {
final text = Text(msg.text);
          if (msg is ImgMessage) {
return Row(
children: <Widget>[
Image.network(msg.imageUrl),
text,
],
);
}
return text;
}).toList(),
);
}
}

MessageList acknowledges a List of Message objects through its constructor, at that point utilizes those to make UI components. Like all Flutter widgets, this one incorporates an overridden build() a strategy that the structure calls during the suitable point in the widget’s lifecycle.

A Column widget shows its children consecutively in an upward section. Every child should be a widget. We utilize the List class’map() technique to create this widget. The map() technique loops through every component of messages, passing each to an unknown function gave as its lone contention. The mysterious function first forms a Text widget, because each message needs that. On the off chance that the current Message object is really an occurrence of ImgMessage, we return a Row that incorporates both the picture and the text widget. Else, we basically return the text widget.

What is Composition in Flutter?:

Inheritance expands a class’s conduct through a class progression, with properties and techniques that went down through the generations. Composition is a more measured methodology wherein a class contains occasions of different classes that carry their own abilities with them. Composition is a way to combine simple objects to create complex ones. For instance, when making a computer you put together a motherboard, CPU, GPU, RAM, and a hard drive. This is composition. In Composition, on the other hand, a class contains instances of other classes which bring their own properties and behavior to the containing class. The composition brings flexibility in building Flutter UI. You put together any number of widgets to achieve any desired UI in your app.

Composition is utilized widely in Flutter’s UI system. If you somehow happened to inspect the code for Flutter’s Container widget, you’d think that it’s made out of numerous different widgets, the specific idea of which relies upon the arguments passed to the Container during launch. We should look again at the MyWidget class from prior:

class MyWidget extends StatelessWidget {
@override
Widget build(BuildContext context) {
return Column(
children: <Widget>[
Container(),
Container(),
Column(),
],
);
}
}

An example of MyWidget is a StatelessWidget, however, one might say, it is made out of a Column, two Container widgets, and a Column. Through structure, we characterize what a MyWidget is. Many Flutter widgets, custom, and center are flimsy coverings around a lot of child widgets. This allows a great deal of flexibility and power when constructing an app’s UI.

Use of Composition child pattern in Flutter:

When building Flutter applications, you’ll regularly experience widgets that take a child an argument. Thusly, widgets are composable. Envision a button widget that acknowledges just a string label. To make the catch’s label adaptable, it would have to acknowledge countless different arguments permitting you to set properties like color, size, and so on, and it could always be unable to deal with everything.

In Flutter, button widgets acknowledge any Widget object as a child. Frequently, it’s a content child, yet it very well may be anything, and the catch doesn’t have to reimplement all the customization choices effectively accessible in Text or different widgets. Through composition, Flutter lets you easily create almost any UI you can imagine. When creating your own widgets, you should keep this pattern in mind.

An instance button instantiation utilizing the child pattern:

FlatButton(
child: Text(
"Done",
style: TextStyle(
color: Colors.red,
fontSize: 15,
),
),
)

Here, we’ve passed an occurrence of the Text widget with a custom style to go about as a label for the FlatButton widget, yet in principle, we might have utilized any widget, even one through our own effort. The child here could be a graph, a map, a symbol, or a picture, to give some examples prospects, as the FlatButton will oblige any widget whatsoever.

Composition In Data Models:

Now and again it bodes well to utilize arrangement rather than inheritance in your information models. For instance, consider a game application where a player should obliterate a progression of vicecity demo. In the first place, you may proclaim a couple of demos for various game types:

class ViceCityDemo {
final int health;
ViceCityDemo({this.health});
}
class GtaCityDemo extends ViceCityDemo {
final int gun;
GtaCityDemo({int health, this.gun}) :
super(health: health);
}
class GameCityDemo extends GtaCityDemo {
final String name;
GameCityDemo({int health, int gun, this.name}) :
super(health: health, gun: gun);
}

For the demo, inheritance is the most ideal alternative, because each game requirements the health property, and more particular games have extra properties. Each particular demo is a ViceCityDemo since they all have that class in their parentage. We could make a collection of these layouts someplace, which we could helpfully type as ViceCityDemo, and it could hold any of our demo occurrences. Note that for brevity, I’ve not included the @required metatag on any parameters, but you certainly should where appropriate.

The demos incorporate just final properties, which implies the properties can’t be adjusted once introduced; fitting for demos. Changeless information models like this are a best practice, yet now we need an approach to adjust a game’s health over the span of a game.

class LiveGame {
final ViceCityDemo demo;
int currentHealth;

LiveGame(this.demo) {
currentHealth = demo.health;
}
}

This class doesn’t extend another. A live game isn’t a demo, so it would be illogical for it to slip from any of the demo classes. Live games need to realize which demo they’re founded on, and they shouldn’t have the option to change a demo’s properties. The changeable property currentHealth is instated from a demo’s health value, and it tends to be altered later to represent wounds since it’s anything but a final property. With this pattern, it’s possible to build any number of LiveGame instances, and each can be built using any of the templates. A live game is composed of a template and a current health value.

Inheritance connections are regularly depicted as is-a connections; a GtaCityDemo is a ViceCityDemo. Composition connections are has-a connections; a LiveGame has a ViceCityDemo. Use all of these concepts when constructing your own classes, remembering that each is best for different situations.

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying up the Inheritance and Composition in Dart & Flutter in your flutter projectsWe will show you what Inheritance and Composition in Dart and Flutter is?. You have just learned how inheritance and composition patterns will work with dart and flutter in your flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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

Related: Exploring Asynchronous Programming In Dart & Flutter

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


Explore Immutable Data Structures In Dart & Flutter

0

In object-oriented and functional programming, an immutable object is an object whose state can’t be adjusted after it is made. This is as opposed to a mutable object, which can be adjusted after it is made. Instances of Java values that are changeless are numbers and strings. Java values that are mutable include objects, arrays, functions, classes, sets, and maps.

In this article, we will Explore Immutable Data Structures In Dart & Flutter. We will take a look at how immutable data structures will work with dart and flutter in your flutter applications.

Table Of Contents::

Immutable Data in Dart

Final Variables vs Constants

Immutable Data in Flutter

Creating Immutable Data Classes

Using Metatag Helper

Complex Objects in Immutable Classes

Immutable Collections

Updating Immutable Data

State Update Functions

State Update Class Methods

Copy Methods

Updating Collections

Conclusion



Immutable Data in Dart:

Immutable data builds are those that can’t be changed after they’ve been introduced. The Dart language is loaded with these. Once made, strings, numbers, and boolean values can’t be mutated. A string variable doesn’t contain string data, itself. Non-final string factors can be reassigned, which directs them toward new string data, yet once made, string data itself doesn’t change substance or length.

var str = "This is a Flutter Devs.";
str = "This is a Aeologic Technologies.";

This code pronounces a string variable called str. The data is set in memory, at that point, a reference to its area is put away in the variable str. The subsequent line makes an all-new string and relegates a reference to its memory area to a similar variable, overwriting the reference to the primary string. The first string isn’t changed; however, on the off chance that there could be no substance in your code at this point, it is set apart as inaccessible, and its memory will ultimately be liberated by Dart’s garbage collector.

Final Variables vs Constants:

The differentiation between Dart’s final and const a word can be fluffy for beginners. While making your own immutable data, it’s imperative to see how they’re unique and where to utilize each.

The final permits just a solitary task. It should have an initializer, and whenever it has been instated with a value, the variable can’t be reassigned

final str = "This is a Flutter Devs.";
str = "This is a Aeologic Technologies."; // error

Dart won’t permit you to change the value of the final factor str. The final variable may depend on runtime execution of code to decide its state, yet it should happen during initialization.

Constants in Dart are compile-time constants. The const word adjusts values. A constant whole deep state should be definite at compile time.

Dart constants share three fundamental properties:

  • > Constant values are profoundly, transitively immutable. On the off chance that you need to make a steady collection (list, map, and so forth), every component should likewise be constant, recursively.
  • > Constant values must be made from data accessible at compile time. For example, DateTime.now() can’t be constant, because it depends on data just accessible at runtime to make itself.
  • > Constants are canonicalized. A solitary item is made in memory for some random consistent value regardless of how frequently the steady articulation is assessed.

A few constant instance are :

const str = "This is a Flutter Devs.";
const SizedBox(width: 5); // a constant object
const [1, 2, 3]; // a constant collection
1 + 2; // a constant expression

The str constant is allocated a string exacting, which are consistently compile-time constants. The SizedBox example made here can be constant and immutable because Dart can set it up before executing the program since the entirety of the properties of SizedBox are final inside and we’re passing an exacting contention(5). The articulation 1 + 2 can be determined by the Dart compiler before executing the code, so it likewise qualifies as steady.

List<int> get list => [1, 2, 3];
List<int> get constList => const [1, 2, 3];

var a = list;
var b = list;
var c = constList;
var d = constList;

print(a == b); // false
print(c == d); // true

Even though a, b, c, and d each reference a list with indistinguishable substance, just the constant variants analyze as true. Dart is contrasting the memory address of the list, not the values of the components. Each call to the constList getter returns a reference to a steady list, yet recall that Dart just places the list into memory once.

Immutable Data in Flutter:

There are where a Flutter application can utilize immutable constructions to improve readability or execution. Bunches of structure classes have been composed to permit them to be built in an immutable structure. Two normal examples are SizedBox and Text.

Row(
children: <Widget>[
const Text("Flutter Devs"),
const SizedBox(width: 10),
const Text("Flutter Devs"),
const SizedBox(width: 10),
const Text("Its a software company?"),
],
)

This Row has been developed with five children. At the point when we utilize the const keyword to make cases of classes that have const constructors, the values are made at compile time and every special value is put away in memory only a single time. The initial two Text examples will make plans to references to a similar object in memory, as will the two SizedBox instances. If we somehow happened to add const SizedBox(width:20), a different constant example would be made for that new value.

Let’s look at another instance:

final size = 15.0;

const Text(
"Flutter Devs",
style: TextStyle(
fontSize: size, // error
),
)

This code snippet has lots occurring. we’re trying to create a constant example of text content, but understand that a legitimate consistent is regular all the way down. The string literal "Flutter Devs"works best. Dart will attempt to create the TextStyle as a steady, TextStyle can not be regular here due to its reliance on the variable size, which would not have a value until runtime. To restoration, this, changing final to const within the declaration of size might additionally do the trick.

Creating Immutable Data Classes:

Creating a simple immutable class magnificence may be as easy as using very final properties and adding const to the constructor.

class Student {
final int rollNum;
final String name;

const Student(this.rollNum, this.name);
}

The Student class has two properties, each declared final, and these are initialized routinely with the aid of the constructor. The constructor makes use of the const key-word to inform Dart it’s okay to instantiate this elegance as a compile-time regular.

const std1 = Student(1, "Sam");
var std2 = const
Student(1, "Sam");
final std3 = const
Student(1, "Sam");

The Simplest one constant instance of the Student is created right here, and each variable is assigned a reference to it. For std1, we don’t need to include the const keyword with the constructor, because its need is at once implied with the aid of our use of it on the variable, even though you could consist of it if you desire. The std2 variable is a normal variable with a sort of Student, however, we’ve assigned it a reference to an immutable, consistent object. The variable std3 is equal to std2 except that it can by no means be assigned a new reference. No matter wherein you pass these references, you may continually ensure that when tested, the object’s rollNum maybe 1 and the call can be “Sam”, and you’ll always be analyzing the identical values in reminiscence.

Using Metatag Helper:

You could use the @immutablemetatag from the meta package to get useful analyzer warnings on classes you ought to be immutable.

import 'package:meta/meta.dart';

@immutable
class Student {
int rollNum; // not final
final String name;

Student(this.id, this.name);
}

The metatag does now not make your elegance immutable, however, in this case, you’ll get a caution declaring that one or greater of your fields aren’t final. In case you attempt to add the const keyword to your constructor at the same time as there are mutable properties, you’ll get an error that tells you essentially the same aspect.

Complex Objects in Immutable Classes:

What if a student’s name was represented by an object more complex than a string? As an instance:

class StudentName {
String first;
String middle;
String last;

StudentName(this.first, this.middle, this.last);
}

So Student would now look like this:

class Student {
final int rollNum;
final StudentName name;
 const Student(this.rollNum, this.name);
}

Generally, the Student works very much as it did previously, with one key contrast. Since we haven’t characterized StudentName as an immutable class, its properties will be liable to change after initialization.

var std = Student(1, StudentName('John', 'Eben', 'Thomas'));
std.name = StudentName('Jane', 'C', 'Disuza');  // blocked
std.name.last = 'Disuza'; // allowed

The name property of Student is final, so Dart keeps it from being reassigned. The properties of StudentName are not ensured similarly, notwithstanding, so changing that information is permitted.

Immutable Collections:

Collections present another challenge to immutability. Indeed, even with a final reference to a List or Map, the components inside those assortments may, in any case, be variable. Likewise, lists and maps in Dart are mutable complex objects themselves, so it can, in any case, be feasible to add, eliminate, or reorder their components.

Consider a simple instance using message data:

class Message {
final int id;
final String text;
  const Message(this.id, this.text);
}
class MessageThread {
final List<Message> messages;
  const MessageThread(this.messages);
}

With this arrangement, the information is genuinely protected. Each message made is changeless, and it’s unrealistic to supplant the list of messages inside MessageThread whenever it’s been initialized.

final thread = MessageThread([
Message(1, "Message 1"),
Message(2, "Message 2"),
]);
thread.messages.first.id = 10;                 // blocked
thread.messages.add(Message(3, "Message 3")); // This works!

=> Return Copy of the Collection

If you wouldn’t fret the calling code accepting an alterable duplicate of the collection, you can utilize a Dart getter to return a duplicate of the expert list at whatever point it’s gotten to from outside the class.

class MessageThread {
final List<Message> _messages;
List<Message> get messages => _messages.toList();
  const MessageThread(this._messages);
}
thread.messages.add(Message(3, "Message 3"));  // new list

With this MessageThread class, the genuine message list is private. A getter named messages is characterized that profits a duplicate of the _messages list. When outside code calls the list’s add() technique, it is doing as such on a different duplicate of the list, so the first isn’t altered.

In the first place, with extremely enormous records or regular access, this could begin to burden execution. A shallow duplicate of the list is made each time messages is gotten to. Second, it tends to be mistaken for users of the class, as it might look to them like they’re permitted to adjust the original list.

=> Return Unmodifiable Collection or View

Any other manner to save you changes on your collections within a data class is to use a getter to return an unmodifiable version or unmodifiable view.

class MessageThread {
final List<Message> _messages;
List<Message> get messages => List.unmodifiable(_messages);
  const MessageThread(this._messages);
}
thread.messages.add(Message(3, "Message 3"));  // exception!

This methodology is basically the same as the recently examined approach. A duplicate of the list is as yet being made, however, now the duplicate we’re returning is unmodifiable. We utilize a factory constructor characterized on Dart’s List class to make the new list. Presently, when the user endeavors to add another message to their duplicate list, a special case is tossed at runtime, and the change is prevented.

import 'dart:collection';
class MessageThread {
final List<Message> _messages;
UnmodifiableListView<Message> get messages =>
UnmodifiableListView<Message>(_messages);
  const MessageThread(this._messages);
}
thread.messages.add(Message(3, "Message 3"));  // exception!

Doing it this way may play out somewhat better because an UnmodifiableListView doesn’t duplicate the original list. All things considered, it envelops the first by a view that forestalls change.

=> Truly Immutable Collections

You can have noticed that each one of our hints for returning immutable versions of collections with getters nonetheless leaves the original collections technically mutable. Code inside the library can manage the structure of the private _messages list.

One approach to accomplish this is to make our unmodifiable version or view as the MessageThread object is developing

class MessageThread {
final List<Message> messages;
  const MessageThread._internal(this.messages);
  factory MessageThread(List<Message> messages) {
return MessageThread._internal(List.unmodifiable(messages));
}
}

The principal thing we need to do is conceal the steady constructor from code outside the library. We change it into a named constructor with a highlight prefix, which makes it private. The MessageThread._internal() a constructor does precisely the same occupation our old default constructor did, however, it must be gotten to by inner code.

We make the default, public constructor a processing factory constructor. factories work a great deal like static strategies, in that they should expressly return an occurrence of the class as opposed to doing so naturally as normal constructors do.

final thread = MessageThread([
Message(1, "Message 1"),
Message(2, "Message 2"),
]);

This actually works, and nobody can tell that they’re calling an industrial facility constructor rather than an ordinary one. By chance, this method resembles the one utilized for the Singleton configuration design in Dart.

Updating Immutable Data:

Whenever you have all your application state securely concealed in permanent constructions, you may be thinking about how it tends to be refreshed. Singular occasions of your classes shouldn’t be alterable, however, the state surely needs to change. As could be, there are a couple of various methodologies, and we’ll investigate some of them here.

State Update Functions:

Quite possibly the most well-known method of updating immutable states is utilizing some sort of state update work. In Redux, this can be a reducer, and there are comparative builds when utilizing the BLoC design for state management.

Beginning with the least complex student, we should take a gander at a couple of conceivable state update capacities for the immutable Student class presented before.

Note that these functions are not part of the Student class:

class Student {
final int rollNum;
final String name;
const Student(this.rollNum, this.name);
}
Student updateStudentRollNum(Student oldState, int rollNum) {
return
Student(rollNum, oldState.name);
}
Student updateStudentName(Student oldState, String name) {
return
Student(oldState.id, name);
}

This example is simple, and it works really hard of ensuring just upheld refreshes are finished. Essentially, each capacity takes a reference to the past student state, at that point it utilizes that and new information to build an all-new case, returning it to the caller.

State Update Class Methods:

You can utilize class strategies rather than discrete, high-level functions on the off chance that you like to keep all that identified with state control with the state code.

class Student {
final int rollNum;
final String name;
const Student(this.rollNum, this.name);

Student updateRollNum(int rollNum) {
return
Student(rollNum, name);
}
Student updateName(String name) {
return
Student(rollNum, name);
}
}

With this methodology, you can be less verbose in your naming, since unmistakably each update strategy has a place with the Student class. Without great code shading, it might look like both update strategies have indistinguishable code, however, updateRollNum() is making another case of Student with the approaching rollNum contention and the old name. The updateName() a strategy is doing the inverse.

Copy Methods:

A typical strategy utilized in Dart and Flutter projects with immutable information is adding a copyWith() technique to a class.

class Student {
final int rollNum;
final String name;
const Student(this.rollNum, this.name);
Student copyWith({int rollNum, String name}) {
return
Student(
rollNum ?? this.rollNum,
name ?? this.name,
);
}
}

The copyWith() technique ought to as a rule utilize named discretionary boundaries without defaults. The return proclamation utilizes Dart’s if invalid operator, ??to decide if the duplicate of student ought to get another incentive for every property or keep the current state’s value. On the off chance that it’s missing or unequivocally set to invalid, this.rollNum will be utilized all things being equal.

final std1 = Student(1, "Jake");
final std2 = std1.copyWith(rollNum: 2);
final std3 = std1.copyWith(name: "Jerry");
final std4 = std1.copyWith(rollNum: 2, name: "Jerry");

When this code executes, thestd2 variable will reference a duplicate of std1 with a refreshed rollNum value yet the name will be unaltered. The std3 duplicate will have another name and the original RollNum. With this Student class, the std4 duplicate activity is indistinguishable from making another object altogether, as it replaces each value.

Student updateStudentRollNum(Student oldState, int rollNum) {
return oldState.copyWith(rollNum: rollNum);
}
Student updateStudentName(Student oldState, String name) {
return oldState.copyWith(name: name);
}

You may even consider the utilization of state update works here to be needless excess, as they’re currently such slim coverings around the call to copyWith().

Updating Collections:

The structure you use to refresh immutable collections depends both on how you’re setting up your collections and the amount of an immutability perfectionist you are.

class NumberList {
final List<int> _numbers;
List<int> get numbers => List.unmodifiable(_numbers);
  NumberList(this._numbers);
}

This class actually has an mutable list, yet just uncovered an unmodifiable duplicate to the rest of the world. To refresh this list with a state update function

NumberList addNumber(NumberList oldState, int number) {
final list = oldState.numbers.toList();
return NumberList(list..add(number));
}

This methodology isn’t very effective. The articulation oldState.numbers convey us a duplicate of the oldState list, however, it’s unmodifiable, so we need to utilize toList() to make one more duplicate, this one changeable.

class NumberList {
final List<int> _numbers;
List<int> get numbers => List.unmodifiable(_numbers);
  NumberList(this._numbers);
  NumberList add(int number) {
return NumberList(_numbers..add(number));
}
}

There are decent things about this technique. It’s less verbose and requires less code. One nuance to know about is that we’re mutating and reusing _numbers.

Conclusion:

In the article, I have explained the basic structure of the Immutable Data Structures In Dart & Flutter; you can modify this code according to your choice. This was a small introduction to Immutable Data Structures In Dart & Flutter On User Interaction from my side, and it’s working using Flutter.

I hope this blog will provide you with sufficient information on Trying up the Immutable Data Structures In Dart & Flutter in your flutter projectsWe will show you what Immutable Data in Dart and Flutter is?. There are numerous methods of taking care of object and collection immutability, and now you ought to be comfortable with a portion of the manners in which the Dart aces approach keeping even complex data from startlingly mutating. So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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

Related: Explore Fluid Slider In Flutter

Related: Explore Sliding Card In Flutter

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


Exploring Asynchronous Programming In Dart & Flutter

0

Asynchronous programming is a type of equal programming that permits a unit of work to run independently from the essential application thread. At the point when the work is finished, it tells the main thread. The UI widgets accessible in the Flutter structure utilize Dart’s asynchronous programming highlights to extraordinary impact, assisting with keeping your code coordinated and keeping the UI from securing on the client.

In this blog, we will be Exploring Asynchronous Programming In Dart & Flutter. We will take a look at how asynchronous code patterns can assist with preparing user interaction and recovering data from a network, and see a couple of asynchronous Flutter widgets in action in your flutter applications.

Table Of Contents::

Asynchronous Programming

Why we should use Asynchronous Programming

Future

Using Await/Async

User Interaction Events

Asynchronous Network Calls Using Callbacks

Asynchronous Network Calls Without Callbacks

FutureBuilder

StreamBuilder

Conclusion



Asynchronous Programming:

It is a type of equal execution that affixes up the chain of events in a programming cycle. For those of you who are new to the universe of asynchronous programming, it is another technique to accelerate the improvement cycle. Be that as it may, we can’t utilize asynchronous programming on all instances. It works in situations when you are searching for straightforwardness over productivity. To deal with basic and autonomous information, asynchronous programming is an extraordinary decision.

Diagram

Dart is the ideal counterpart for Flutter from various perspectives, in any event, for asynchronous programming. Even though Dart is single-threaded, it can associate with different codes that run in discrete threads. The utilization of synchronous code in Dart can create delays and block your whole program execution. Be that as it may, asynchronous programming tackles this issue. Furthermore, this prompts improved application execution and application responsiveness.

Why we should use Asynchronous Programming:

There are some uses of Asynchronous Programming are:

  • > Improvement in performance and responsiveness of your application, especially when you have long-running activities that don’t need to block the execution. For this situation, you can perform other work while waiting for the outcome from the long-running undertaking.
  • > Assemble your code in a flawless and comprehensible manner fundamentally better than the standard code of the conventional thread creation and taking care of it with async / await , you compose less code and your code will be more viable than utilizing the past asynchronous programming strategies like utilizing plain assignment.
  • > You utilize the most recent upgrades of the language highlights, as async / await was presented in a flutter.
  • > There have been a few improvements added to the element like for each async and summed up async type like Value.

Future:

How the future works are basically the same as Promise from Javascript. It has two expresses that are Uncompleted and Completed. The completed Future will have either value or mistake. The uncompleted future is waiting that the function’s asynchronous activity will complete or to throw a mistake.

The class has a few constructors:

  • > Future. delayed implies acknowledges a Duration object as contentions demonstrating the time span and a function to be executed after delay.
  • > Encoded memory cache implies stores compressed pictures in the original state in memory.
  • > Future. error() implies makes a Future that finishes with a mistake.

Using Await/Async:

The async and await approaches in Dart are basically the same as different dialects, However, regardless of whether you don’t have insight with asynchronous programming utilizing async/await, you should think that it’s simple to follow here.

=> Async functions: Functions structure the foundation of asynchronous programming. These async functions have async modifiers in their body. Here is an illustration of a general async work underneath:

void flutter() async {

print('Flutter Devs');

}

=> Await expressions: It makes you compose the asynchronous code as though it were simultaneous. All in all, an await articulation has the structure as given beneath:

void main() async {

await flutter();

print('flutter Devs done');

}

User Interaction Events:

Maybe the easiest model for asynchronously handling user input is responding to connection events on a button widget with callbacks:

FlatButton(
child: Text("Data"),
onPressed: () {
print("pressed button");
},
)

The FlatButton widget, as most catch like Flutter widgets, gives a comfort boundary called onPressed for reacting to fasten presses. Here, we’ve passed a mysterious callback capacity to the boundary that does nothing besides printing a message to the console. At the point when the client presses the catch, the onPressed event is set off, and the unknown function will be executed when the occasion loop can get to it.

In the background, there is an event stream, and each time another event is added to it, your callback work is called with any pertinent information. For this situation, a basic catch press has no related information, so the callback takes no boundaries.

Asynchronous Network Calls Using Callbacks:

Perhaps the most well-known cases for asynchronous programming includes getting information over a network, for example, through a REST service over HTTP:

import 'package:http/http.dart' as http;

final future = http.get("https://flutterdevs.com");

future.then((response) {
if (response.statusCode == 200) {
print("Response received.");
}
});

The http package is among the most well-known on Dart’s package repos, Pub. I’ve incorporated the import an assertion here to call attention to the average example of namespacing the import with the name http utilizing the as keyword. These aides keep the package’s many high-level functions, constants, and factors from conflicting with your code, just as clarifying where functions likeget() come from.

The code model shows the classic example for devouring a future. The call to http.get() promptly returns an inadequate Future example when called. Recollect that obtaining results throughout HTTP requires some serious energy, and we don’t need our application to be inert while we stand by. That is the reason we move the future back immediately and continue with executing the following lines of code. Those next lines utilize the Future example’s at that then() strategy to enlist a callback that will be executed when the REST reaction comes in sooner or later. On the off chance that the inevitable response has an HTTP status code of 200 (success), we print a straightforward message to the debug console.

How about we refine this example as a piece. That model stores the future in a final variable to get then(), yet except if you have a valid justification to keep that future case around, it’s average to skip that part, as in the accompanying model:

http.get("https://flutterdevs.com").then((response) {
if (response.statusCode == 200) {
print("Response received.");
}
else {
print("Response not received");
}
});

Since the call to get() takes steps to a Future, you can call its then()strategy on it straightforwardly, without saving the future reference in a variable. The code is a bit more minimal along these lines, yet at the same time decipherable. It’s feasible to chain a few valuable callback registrations onto our future, as so:

http.get("https://flutterdevs.com").then((response) {
if (response.statusCode == 200) {
print("Response received.");
}
else {
print("Response not received");
}
}).catchError(() {
print("Error!");
}).whenComplete(() {
print("Future complete.");
});

Presently we’ve enlisted a callback to be executed when the HTTP call closes with a mistake rather than a response utilizing catchError, and another that will run paying little mind to how the future finishes utilizing whenComplete(). This technique tying is conceivable because every one of those strategies returns a reference to what’s to future we’re working with.

Asynchronous Network Calls Without Callbacks:

Dart offers a substitute example for settling on asynchronous calls, one that looks more like customary synchronous code, which can make it simpler to peruse and reason about. The async/await punctuation handles a great deal of the logistics of futures for you:

Future<String> getData() async {
final response = await http.get("https://flutterdevs.com");
return response.body;
}

At the point when you realize you’ll play out an asynchronous call inside a function, for example, http.get()you can stamp your function with the async keyword. An async work consistently returns a future, and you can utilize the await keyword inside its body. For this situation, we realize the REST call will return string information, so we use generics on our return type to indicate this: Future<String>.

You can await any function that returns a future. The getData() function will suspend execution following the await articulation runs and returns a future to the caller. The code waits tight for a reaction; it waits for the network call’s future to finish. Afterward, when the reaction comes in absurd, execution resumes, and the Response object is appointed to the last factor, then getData() returns response.body, which is a string. You don’t have to expressly return a future from getData(), because one is consequently returned on the main utilization of await. When you have the string information, you return that, and Dart finishes the future with the worth.

To catch errors when utilizing await, you can utilize Dart’s standard try/catch include:

Future<String> getData() async {
try {
final response = await http.get("https://flutterdevs.com");
return response.body;
} catch (excute) {
print("Error: $excute");
}
}

In this version, we place code that could throw exemptions into the try block. In the case of everything goes easily, we’ll get a response and return the string information, similarly as in the earlier model. In case of an error, the catch block will execute all things considered, and we’ll be passed a reference to the exemption. Since we haven’t added an express return proclamation to the furthest limit of getData(), Dart will add a certain return null statement there, which will finish the future with a null worth.

Note that if the network call succeeds, the return occurs in the try block, so the implied return will not be summoned.

Callbacks have their utilizations, and they can be an extraordinary method to deal with asynchronous correspondence for straightforward cases, for example, responding to a client squeezing a catch. For more confounded situations, for example, when you need to settle on a few asynchronous calls in arrangement, with each relying upon the consequences of the earlier call, Dart’s async/await the syntax structure can assist you with trying not to settle callbacks, a circumstance here and there alluded to as callback hellfire.

FutureBuilder:

A FutureBuilder assembles itself dependent on the condition of a given future. For this model, we should expect you have a function called getData() that returns a Future<String>.

class MyStatelessWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return FutureBuilder(
      future: getData(),
      builder: (BuildContext context, AsyncSnapshot snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return CircularProgressIndicator();
        }
   if (snapshot.hasData) {
          return Text(snapshot.data);
        }
   return Container();
      },
    );
  }
}

This custom stateless widget returns a FutureBuilder that will show an advancement pointer if the future returned by getData() has not yet finished, and it will show the information if the future has finished with a value. On the off chance that neither of those things is valid, a vacant Container is delivered all things considered. You advise the FutureBuilder which future to watch with its future boundary, at that point give it a builder work that will be required each modifies. The builder callback gets the typical BuildContext contention normal to all Flutter build activities, and it likewise takes an occurrence of AsyncSnapshot, which you can use to check the future’s status and recover any information.

There is an issue with this methodology. As per the official documentation for FutureBuilder, the gave future necessities to have been gotten preceding the build step.

To fix it, we need to use a stateful widget instead:

class MyStatefulWidget extends StatefulWidget {
@override
_MyStatefulWidgetState createState() => _MyStatefulWidgetState();
}

class _MyStatefulWidgetState extends State<MyStatefulWidget> {
Future<String> _dataFuture;

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

_dataFuture = getData();
}

@override
Widget build(BuildContext context) {
return FutureBuilder(
future: _dataFuture,
builder: (BuildContext context, AsyncSnapshot snapshot) {
if (snapshot.connectionState == ConnectionState.waiting) {
return CircularProgressIndicator();
}

if (snapshot.hasData) {
return Text(snapshot.data);
}

return Container();
},
);
}
}

This adaptation of the widget gains the information future during initState(). The initState() the technique will be called precisely once when the widget’s state object is made.

StreamBuilder:

A stream resembles an event pipe. Information or error events go toward one side, and they are conveyed to listeners on the other. At the point when you give a StreamBuilder a reference to a current stream, it consequently subscribes and withdraws to refreshes as vital, and it assembles itself dependent on any information that needs to be a pipe.

class MyStatelessWidget extends StatelessWidget {
  final Stream<String> dataStream;

 const MyStatelessWidget({Key key, this.dataStream}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    return StreamBuilder<ConnectionState>(
      stream: dataStream,
      builder: (BuildContext context, AsyncSnapshot<ConnectionState> snapshot) {
        if (snapshot.connectionState == ConnectionState.waiting) {
          return CircularProgressIndicator();
        }   if (snapshot.hasData) {
          return Text(snapshot.data);
        }
      return Container();
      },
    );
  }
}

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying up the Asynchronous Programming In Dart & Flutter in your flutter projectsWe will show you what Asynchronous Programming is?. We’ve perceived how you can utilize asynchronous patterns to interact with Flutter system code and Dart’s center libraries, which will assist you with benefiting from those tools. So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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

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


Persistent Bottom Sheet In Flutter

0

The bottom sheet has become an exceptionally well-known spot for fast communications that don’t need a full screen to do. Pursuing a pamphlet, parting a bill, making an installment, sharing something, a pursuit box that prompts another page of results. It gives indications that the makers of the application put thought into how and when certain highlights will be utilized.

In this blog, we will explore the Persistent Bottom Sheet In Flutter. We will implement a persistent bottom sheet demo program and how to create a bottom sheet in your flutter applications.

Table Of Contents::

Persistent Bottom Sheet

Code Implement

Code File

Conclusion



Persistent Bottom Sheet:

It shows the bottom sheet actually like some other view present on the UI format. As the name recommends, its essence is constant i.e., it coincides with the application principle UI region. It works with clients by showing applicable application content and permits collaboration in that locale at the same time. Developers utilize this BottomSheet to show menus, any sort of auxiliary content, or other supporting content for the application.

If you wish to show a persistent bottom sheet, use Scaffold.bottomSheet. To make a persistent bottom sheet that isn’t a LocalHistoryEntry and doesn’t add a back button to the encasing Scaffold’s application bar, utilize the Scaffold.bottomSheetconstructor parameter.

Demo Module :

This demo video shows how to create a persistent bottom sheet in a flutter. It shows how the persistent bottom sheet will work in your flutter applications. When the user taps the button then, the bottom sheet will occur down to up on your screen, and when the user dismissed the sheet using the back button or drag downwards. It will be shown on your device.

How to implement code in dart file :

You need to implement it in your code respectively:

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

In the body part, we will add a Center widget. In this widget, we will add a RaisedButton(). Inside the button, we will add the color of the button, OnPressed function and its child property add a text.

Center(
child: RaisedButton(
color: Colors.teal[100],
onPressed: (){},
child: Text("Show Persistent BottomSheet",
style: TextStyle(color: Colors.black),
),
)),

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

Home Screen

We will create a final _scaffoldKey is equal to the Globalkey<ScaffoldState>(). This key was added to the Scaffold() and without adding the key, the persistent bottom sheet will not work.

final _scaffoldKey = new GlobalKey<ScaffoldState>();

We will create a VoidCallback _showPersistantBottomSheetCallBack means a signature of callbacks that have no arguments and return no data.

VoidCallback _showPersistantBottomSheetCallBack;

We will add initState() method. In this method, we will add _showPersistantBottomSheetCallBack is equal to the _showBottomSheet.

@override
void initState() {
super.initState();
_showPersistantBottomSheetCallBack = _showBottomSheet;
}

We will deeply define _showBottomSheet method:

In this method, we will add a setState() function. In this function, we will add _showPersistantBottomSheetCallBac is equal to null. We will add a _scaffoldKey.currentState.showBottomSheet(context) and return a container widget. In this widget, we will add color and its child property add a text. When complete then add setState() function. In this function, we will add _showPersistantBottomSheetCallBack is equal _showBottomSheet.

void _showBottomSheet() {
setState(() {
_showPersistantBottomSheetCallBack = null;
});

_scaffoldKey.currentState
.showBottomSheet((context) {
return new Container(
height: 200.0,
color:Colors.teal[100],
child: Center(
child: Text("Drag Downwards Or Back To Dismiss Sheet",
style: TextStyle(fontSize: 18,color: Colors.black),
textAlign: TextAlign.center,),
),
);
})
.closed
.whenComplete(() {
if (mounted) {
setState(() {
_showPersistantBottomSheetCallBack = _showBottomSheet;
});
}
});
}

Now, we add _showPersistantBottomSheetCallBack on the onPressed function on RaisedButton. When the user taps the button then, the persistent bottom sheet will occur on your screen, and when you drag downward or use the back button to dismiss the persistent bottom sheet.

onPressed: _showPersistantBottomSheetCallBack,

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

Final Output

Code File:

import 'package:flutter/material.dart';

class BottomSheetDemo extends StatefulWidget {
@override
_BottomSheetDemoState createState() => new _BottomSheetDemoState();
}

class _BottomSheetDemoState extends State<BottomSheetDemo> {
final _scaffoldKey = new GlobalKey<ScaffoldState>();
VoidCallback _showPersistantBottomSheetCallBack;

@override
void initState() {
super.initState();
_showPersistantBottomSheetCallBack = _showBottomSheet;
}

void _showBottomSheet() {
setState(() {
_showPersistantBottomSheetCallBack = null;
});

_scaffoldKey.currentState
.showBottomSheet((context) {
return new Container(
height: 200.0,
color:Colors.teal[100],
child: Center(
child: Text("Drag Downwards Or Back To Dismiss Sheet",
style: TextStyle(fontSize: 18,color: Colors.black),
textAlign: TextAlign.center,),
),
);
})
.closed
.whenComplete(() {
if (mounted) {
setState(() {
_showPersistantBottomSheetCallBack = _showBottomSheet;
});
}
});
}



@override
Widget build(BuildContext context) {
return new Scaffold(
backgroundColor: Colors.grey[200],
key: _scaffoldKey,
appBar: AppBar(
backgroundColor: Colors.cyan[200] ,
title: Text("Flutter Persistent BottomSheet"),
),
body: Padding(
padding: const EdgeInsets.all(20.0),
child: Center(
child: RaisedButton(
color: Colors.teal[100],
onPressed: _showPersistantBottomSheetCallBack,
child: Text("Show Persistent BottomSheet",
style: TextStyle(color: Colors.black),
),
)),
),
);
}
}

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying up the Persistent Bottom Sheet in your flutter projectsWe will show you what the Persistent Bottom Sheet is?. Make a demo program for working Persistent Bottom Sheet and It displays when the user taps the button then, the bottom sheet will occur down to up on your screen, and when the user dismissed the sheet only using the back button or drag downwards in your flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.

find the source code of the Flutter Persistent Bottom Sheet Demo:

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


From Our Parent Company Aeologic

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

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

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

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

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


Exploring AnimatedModalBarrier In Flutter

0

Animation is an amazing and significant idea in Flutter. We can’t envision any mobile application without animations. At the point when you tap on a catch or move starting with one page then onto the next page are altogether animations. Animations improve client encounters and make the applications more interactive.

There are heaps of ways Flutter makes it simple to make animations, from fundamental Tweens to Implicit Animations that are incorporated directly into the structure. Furthermore, assuming those don’t meet your requirements, there are outsider arrangements that do almost anything you can envision.

In this blog, we will be Exploring AnimatedModalBarrier In Flutter. We will see how to implement a demo program of the animated modal barrier and how to use it in your flutter applications.

AnimatedModalBarrier class – widgets library – Dart API
A widget that prevents the user from interacting with widgets behind itself, and can be configured with an animated…api. flutter.dev

Table Of Contents::

AnimatedModalBarrier

Constructor

Properties

Code Implement

Code File

Conclusion



AnimatedModalBarrier:

It is a widget that incapacitates communications with the widgets behind itself. It’s like a non-animated ModalBarrier, however, it permits you to set an Animaton<Color> so you can make an animation impact when the boundary is being appeared.

It keeps the user from connecting with widgets behind itself and can be arranged with an animated color value. The modal barrier is the scrim that is delivered behind each route, which by and large keeps the client from collaborating with the course underneath the current route, and typically part of the way clouds such routes.

Demo Module :

This demo video shows how to use an animated modal barrier in a flutter. It shows how the animated modal barrier will work using the AnimatedModalBarrier class in your flutter applications. It shows when the user taps a button, then behind the button color will be animated and animation effect show and also the color was changing. It will be shown on your device.

Constructor:

There are constructor of AnimatedModalBarrier are:

const AnimatedModalBarrier({
Key key,
Animation<Color> color,
this.dismissible = true,
this.semanticsLabel,
this.barrierSemanticsDismissible,
})

In the above constructor, all fields set apart with @required should not be vacant argument is really needed since you will get an affirmation error on the off chance that you don’t pass it.

Properties:

There are some properties of AnimatedModalBarrier are:

  • > key: This property represents how one widget should replace another widget in a tree.
  • > color: This property will set up the barrier color with this color.
  • dismissible: This property will define whether touching the barrier will pop the current route of the Navigator.
  • semanticsLabel: This property is used for the barrier if it is dismissible. It is read out by accessibility tools.
  • barrierSemanticsDismissible: This property will specify the semantic modal that is included in the semantic tree or not.

How to implement code in dart file :

You need to implement it in your code respectively:

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

In the body part, we will add Builder() method. In this method, we will add a center widget. Inside, we will add a column and its children widget we will add Container. It’s child property, we will add Stack() method. Inside, we will add the buildList(context) methodWe will deeply define below the code.

Builder(
builder: (context) => Center(
child: Padding(
padding: EdgeInsets.all(15.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
height: 100.0,
width: 250.0,
child: Stack(
alignment: AlignmentDirectional.center,
children: buildList(context),
),
),
],
),
),
),
),

We will deeply define buildList(context) method:

We will create a list of widgets. In this widget, we will add a RaisedButton(). In this button, we will add text, color, padding, and the OnPressed function. In this function, we will show the snackbar.

List<Widget> buildList(BuildContext context) {
List<Widget> widgets = <Widget>[
RaisedButton(
padding: EdgeInsets.only(left: 40,right: 40),
color: Colors.teal[200],
child: Text('Press'),
onPressed: () {

Scaffold.of(context).showSnackBar(
SnackBar(content: Text('Button is press'),
backgroundColor: Colors.black,),
);
},
),
];
return widgets;
}

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

Main Screen

You need to make an AnimationController. A TickerProvider is needed for the vsync argument, so you need to have a State class that extends TickerProviderStateMixin.

class _AnimatedDemoScreenState extends State<AnimatedDemoScreen>
with SingleTickerProviderStateMixin {
bool _isLoading = false;
Widget _animatedModalBarrier;

AnimationController _animationController;
Animation<Color> _colorAnimation;

We will create initState() method. In this method, You can utilize ColorTweento characterize the color toward the start and end. In the AnimationController, set the duration of how long the animation will be played. To make the Animaton<Color>, utilize the ColorTween’s animate method and pass the regulator as the contention. From that point onward, pass the Animaton<Color>, as the color contention of AnimatedModalBarrier.

@override
void initState() {
ColorTween _colorTween = ColorTween(
begin: Color.fromARGB(200, 155, 120, 155),
end: Color.fromARGB(100, 127, 127, 127),
);

_animationController = AnimationController(
vsync: this,
duration: const Duration(seconds: 3)
);
_colorAnimation = _colorTween.animate(_animationController);

_animatedModalBarrier = AnimatedModalBarrier(
color: _colorAnimation,
dismissible: true,
);

super.initState();
}

Now, we will add some functions to the buildList(context) method. In the onPressed function, we will add the setState() method and add _isLoading is true, then the animation will start. Also, we will add _animationController was reset and forward. We will add future delayed duration for five seconds and inside setState() we will add _isLoading is false. Then an animation will stop after five seconds.

onPressed: () {
setState(() {
_isLoading = true;
});

_animationController.reset();
_animationController.forward();

Scaffold.of(context).showSnackBar(
SnackBar(content: Text('Button is press'),
backgroundColor: Colors.black,),
);

Future.delayed(const Duration(seconds: 5), () {
setState(() {
_isLoading = false;
});
});
},
),
];

if (_isLoading) {
widgets.add(_animatedModalBarrier);
}

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

Final Output

Code File:

import 'dart:async';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

class AnimatedDemoScreen extends StatefulWidget {
@override
State<StatefulWidget> createState() => _AnimatedDemoScreenState();
}

class _AnimatedDemoScreenState extends State<AnimatedDemoScreen>
with SingleTickerProviderStateMixin {
bool _isLoading = false;
Widget _animatedModalBarrier;

AnimationController _animationController;
Animation<Color> _colorAnimation;

@override
void initState() {
ColorTween _colorTween = ColorTween(
begin: Color.fromARGB(200, 155, 120, 155),
end: Color.fromARGB(100, 127, 127, 127),
);

_animationController = AnimationController(
vsync: this,
duration: const Duration(seconds: 3)
);
_colorAnimation = _colorTween.animate(_animationController);

_animatedModalBarrier = AnimatedModalBarrier(
color: _colorAnimation,
dismissible: true,
);

super.initState();
}

List<Widget> buildList(BuildContext context) {
List<Widget> widgets = <Widget>[
RaisedButton(
padding: EdgeInsets.only(left: 40,right: 40),
color: Colors.teal[200],
child: Text('Press'),
onPressed: () {
setState(() {
_isLoading = true;
});

_animationController.reset();
_animationController.forward();

Scaffold.of(context).showSnackBar(
SnackBar(content: Text('Button is press'),
backgroundColor: Colors.black,),
);

Future.delayed(const Duration(seconds: 5), () {
setState(() {
_isLoading = false;
});
});
},
),
];

if (_isLoading) {
widgets.add(_animatedModalBarrier);
}

return widgets;
}

@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blueGrey[100],
appBar: AppBar(
backgroundColor: Colors.black,
automaticallyImplyLeading: false,
title: Text('Flutter AnimatedModalBarrier Demo'),
),
body: Builder(
builder: (context) => Center(
child: Padding(
padding: EdgeInsets.all(15.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Container(
height: 100.0,
width: 250.0,
child: Stack(
alignment: AlignmentDirectional.center,
children: buildList(context),
),
),
],
),
),
),
),
);
}
}

Conclusion:

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

I hope this blog will provide you with sufficient information in Trying up the AnimatedModalBarrier in your flutter projects. We will show you what the AnimatedModalBarrier is?, some properties and conductor using in AnimatedModalBarrier, and make a demo program for working AnimatedModalBarrier and show when the user taps a button, then behind the button color will be animated and animation effect show and also the color was changing using the AnimatedModalBarrier class in your flutter applications, So please try it.

❤ ❤ Thanks for reading this article ❤❤


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

Clap 👏 If this article helps you.

find the source code of the Flutter Animated Modal Barrier Demo:

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

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

From Our Parent Company Aeologic

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

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

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 FacebookGitHubTwitter, 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: Show/Hide Password Using Riverpod In Flutter

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


Explore Generics In Dart & Flutter

0

Flutter code utilizes Dart generics everywhere to guarantee object types are what we anticipate that they should be. Basically, generics are an approach to code a class or capacity so it works with a scope of information types rather than only one while remaining sort-safe. The type the code will work with is indicated by the caller, and along these lines, type safety is kept up.

In this article, we will Explore Generics In Dart & Flutter. We will perceive how to utilize generics collections, classes, and functions in your flutter applications.

Table Of Contents::

Introduction

Generics with Collections

Generics with Asynchronous

Generics in Flutter

Generic Methods & Functions

Generic Classes

Conclusion



Introduction:

Generics are utilized to apply more grounded type checks at the compile time. They implement type-safety in code. For instance, in collections, the type-safety is authorized by holding a similar kind of information. Generics help composes reusable classes, methods/functions for various information types.

Collectionsstreams, and futures are the center library highlights you’ll use with generics frequently as you compose Flutter applications with Dart. It’s a positive routine to exploit generics any place they’re accessible. It’s additionally critical to have the option to believe that information that emerging from prospects or streams has the correct construction, and Dart’s generics include permits you to indicate what that design ought to be.

Generics with Collections:

Collection generics can assist you with being sure every component inside a collection is of the normal kind. You can proclaim collection factors without generics like this:

List myList;
Map myMap;

That code is identical to the accompanying:

List<dynamic> myList;
Map<dynamic, dynamic> myMap;

This ought to possibly be done when you truly need a collection containing a wide range of types. If you know the expected kind of list’s components, you ought to indicate that type inside the angle brackets, which will permit the Dart analyzer to assist you with keeping away from mistakes:

List<String> myList;

Likewise, in the event that you expect for a map to contain keys and values of a specific sort, remember them for the revelation:

Map<String, dynamic> jsonData;
Map<int, String> myMap;

With maps, the primary type inside the angle brackets obliges the map’s keys while the second does likewise for the guide’s qualities. It ought to be noticed that Dart permits you to utilize any sort of map keys, while in certain languages just strings are permitted.

Generics with Asynchronous:

We utilize asynchronous activities to permit an application to stay responsive while trusting that moderately extensive tasks will finish. Instances of tasks that require some time in this manner may be getting information over a network, working with the document framework, or getting to a database. Dart’s essential development supporting asynchronous programs are the Future and the Stream.

It’s a best practice to incorporate kinds when managing futures and streams. This holds them back from returning information of some unacceptable kind. As in different circumstances, if you neglect to incorporate a particular kind, dynamic is expected, and any sort will be permitted.

=> Futures:

It addresses the consequence of asynchronous activity. At the point when at first made, a future is uncompleted. When the activity is finished, what’s to come is finished either with a worth or an error. Utilizing generics, we can indicate the normal type of significant value that is created.

This function returns a Future, yet a bool is at last delivered when the future finishes:

Future<bool> someData() {
return Future.delayed(const Duration(seconds: 2 ), () => true);
}

=> Streams:

They resemble an asynchronous list, or an information pipe, conveying an asynchronous grouping of information. As values become accessible, they are embedded into the stream. Listeners on the stream get the values in a similar request they were embedded.

A typical method to permit a class to communicate with outside code is to utilize a StreamController joined with a Stream. Adding generic sort assignments to these is a decent method to ensure they don’t convey unforeseen outcomes:

final _onData= StreamController<Data>.broadcast();
Stream<Data> get onData => _onData.stream;

This code makes a StreamController that can be utilized to send “Data” objects out on a Stream asynchronously.

Generics in Flutter:

The most widely recognized spots you’ll utilize generics in Flutter are in collections and stateful widgets. Stateful widgets have both a StatefulWidget class and a going with State class. The State class utilizes generics to ensure it manages the StatefulWidget it has a place with, utilizing the syntax structure State<MyApp>. A State case is conventional, composed to work with any StatefulWidget, and for this situation, we’re making a state explicitly for our MyApp class.

class MyApp extends StatefulWidget {
@override
_MyAppState createState() => _MyAppState();
}

class _MyAppState extends State<MyApp> {
@override
Widget build(BuildContext context) {
return Row(
children: <Widget>[
const Text("Hello, "),
const Text("Flutter Dev's"),
],
);
}
}

If you somehow managed to leave off the angle brackets and the MyApp symbol, the analyzer wouldn’t say anything negative, yet you would have made a State attached to the default dynamic type. In addition to the fact that this is not type-safe, however, it could make issues for the framework as it attempts to coordinate with state cases to the right widgets.

The List strict passed to children for the Row widget is comparatively composed, this time as a list of Widget objects: <Widget>[]. This assignment assists Dart with getting issues at configuration time. If you attempt to put a non-widget into that collection, you will get alerts.

A Row doesn’t have the foggiest idea of how to manage objects that aren’t widgets, so getting this sort of issue before your code runs is helpful. The generics additionally serve to make code that is more self-reporting, clarifying what’s generally anticipated inside the collection.

Generic Methods & Functions:

Dart upholds the utilization of generics on methods and functions. This can prove to be useful when you have an activity to perform and you would prefer not to compose a few unique renditions of that activity to help different types.

Assume you need to make a generic function that can change over string esteem into an enum. Generics can assist you with abstaining from utilizing dynamic, guarding your return type safe:

enum Size {
small,
medium,
large
}

T stringToEnum<T>(String str, Iterable<T> values) {
return values.firstWhere(
(value) => value.toString().split('.')[1] == str,
orElse: () => null,
);
}

Size size = stringToEnum<Size>("large", Size.values);

In the above code, T addresses the type to be given by the caller of stringToEnum(). That type will be utilized as the function’s return type, so when we call the function on the last line, the size will be securely composed. By chance, T will be given to the values boundary type, guaranteeing that only the right sorts will be acknowledged in the Iterable collection. The stringToEnum() function will work in a type-safe path for any enum. The gave string doesn’t coordinate with any of the enum values, and null will be returned.

Generic Classes:

You will likewise need to try not to make separate classes for the sole motivation behind dealing with various information types. Maybe you need to make a specific collection class, and still, keep up type safety.

class Data<T> {
List<T> _data = [];

void push(T item) => _data.add(item);
T pop() => _data.removeLast();
}

This class furnishes you with a collection that will never really push things onto data and pop them off. It’s difficult to get to the data’s values straightforwardly from outside a case, as the _data property is private.

final data = Data<String>();

data.push("A string."); // works
data.push(5); // errors

This data won’t permit a value of some unacceptable type to be added. Furthermore, the pop() technique will create a value with a coordinating with the return type.

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying up the Generics In Dart & Flutter in your flutter projectsWe will show you what the Introduction is? and you’ve learned about utilizing generics to expand type safety within your applications, which will prompt fewer type-related errors and fewer terrible surprises for your users in your flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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

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


How To Get Unique Device Details In Flutter?

0

In general, making a mobile application is an extremely mind-boggling and testing task. There are numerous frameworks available, which give magnificent highlights to create mobile applications. For creating mobile applications, Android gives a native structure framework on Java and Kotlin language, while iOS gives a system dependent on Objective-C/Swift language.

Subsequently, we need two unique languages and structures to create applications for both OS. Today, to beat structure this intricacy, several frameworks have presented that help both OS along desktop applications. These sorts of the framework are known as cross-platform development tools.

In this blog, we will explore How To Get Unique Device Details In Flutter?. We will implement a demo program and get unique device details for both Android and IOS using the device_info package in your flutter applications.

device_info | Flutter Package
Get current device information from within the Flutter application. Import package:device_info/device_info.dart…pub.dev

Table Of Contents::

Introduction

Implementation

Code Implement

Code File

Conclusion



Introduction:

Flutter gives get current device data from inside the Flutter application. How to get unique device details for both Android and IOS in flutter utilizing the device_info plugin. At the point when we talk about a unique device detail in native, we are having Settings.Secure.ANDROID_ID to get a one-of-a-kind device detail.

Demo Module :

This demo video shows how to get a unique device detail in a flutter. It shows how the device detail will work using the device_info package in your flutter applications. It shows when the user tap on the raised button, the unique device Andriod/Ios information like device name, version, identifier, etc shown on your screen. It will be shown on your device.

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:
flutter:
sdk: flutter
device_info:

Step 2: Import

import 'package:device_info/device_info.dart';

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

How to implement code in dart file :

You need to implement it in your code respectively:

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

First, we will create a UI. In the body part, we will add a center widget. Inside, we will add a column widget. In this widget, we will add a mainAxisAlignmnet was center. It’s children’s property, add a RaisedButton(). In this button, we will add padding, color, and the OnPressed function. It’s child property, we will a text “Device Details”.

Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
RaisedButton(
padding: EdgeInsets.all(14),
color: Colors.cyan[50],
onPressed: (){},
child: Text("Device Details",
style: TextStyle(color: Colors.black),),
),
],
),
),

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

Main Screen

We will create three strings deviceName, deviceVersion, and identifier.

String deviceName ='';
String deviceVersion ='';
String identifier= '';

Now, we will add the main function of the program. We will add future _deviceDetails(). Inside, we will add a final DeviceInfoPlugin is equal to the new DeviceInfoPlugin(). We will add the try{}method and we will import dart: io for the platform.

import 'dart:io';

If the platform is Andriod then, the build is equal deviceInfoPlugin for andriod info. Add a setState() method. In this method, we will add all string is equal to the build. Else if the platform is Ios then, the build is equal deviceInfoPlugin for ios info. Add a setState() method. In this method, we will add all string is equal to the build.

Future<void>_deviceDetails() async{
final DeviceInfoPlugin deviceInfoPlugin = new DeviceInfoPlugin();
try {
if (Platform.isAndroid) {
var build = await deviceInfoPlugin.androidInfo;
setState(() {
deviceName = build.model;
deviceVersion = build.version.toString();
identifier = build.androidId;
});
//UUID for Android
} else if (Platform.isIOS) {
var data = await deviceInfoPlugin.iosInfo;
setState(() {
deviceName = data.name;
deviceVersion = data.systemVersion;
identifier = data.identifierForVendor;
});//UUID for iOS
}
} on PlatformException {
print('Failed to get platform version');
}

}

We will import services for PlatformException

import 'package:flutter/services.dart';

Now, we will add _deviceDetails() onPressed functon on the raised button

onPressed: (){
_deviceDetails();
},

We will add the device version, name, and the identifier is not empty then show a Column widget. In this widget, we will add all three text like Device Name, Device Version, and Device Identifier will be shown on your device. Otherwise, show an empty container.

deviceVersion.isNotEmpty && deviceName.isNotEmpty
&& identifier.isNotEmpty?
Column(
children: [
SizedBox(height: 30,),
Text("Device Name:- "+deviceName,style: TextStyle
(color: Colors.red,
fontWeight: FontWeight.bold)),
SizedBox(height: 30,),
Text("Device Version:- "+deviceVersion,style: TextStyle
(color: Colors.red,
fontWeight: FontWeight.bold)),
SizedBox(height: 30,),
Text("Device Identifier:- "+identifier,style: TextStyle
(color: Colors.red,
fontWeight: FontWeight.bold)),
SizedBox(height: 30,),
],
): Container(),

When the user taps the button then, all three data will be shown on your device. When we run the application, we ought to get the screen’s output like the underneath screen capture.

Final Output

Code File:

import 'dart:io';
import 'package:device_info/device_info.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';

class DeviceDetailDemo extends StatefulWidget {


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

class _DeviceDetailDemoState extends State<DeviceDetailDemo> {

String deviceName ='';
String deviceVersion ='';
String identifier= '';

Future<void>_deviceDetails() async{
final DeviceInfoPlugin deviceInfoPlugin = new DeviceInfoPlugin();
try {
if (Platform.isAndroid) {
var build = await deviceInfoPlugin.androidInfo;
setState(() {
deviceName = build.model;
deviceVersion = build.version.toString();
identifier = build.androidId;
});
//UUID for Android
} else if (Platform.isIOS) {
var data = await deviceInfoPlugin.iosInfo;
setState(() {
deviceName = data.name;
deviceVersion = data.systemVersion;
identifier = data.identifierForVendor;
});//UUID for iOS
}
} on PlatformException {
print('Failed to get platform version');
}

}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.redAccent[100],
title: Text("Flutter Device Details Demo"),
automaticallyImplyLeading: false,
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
RaisedButton(
padding: EdgeInsets.all(14),
color: Colors.cyan[50],
onPressed: (){
_deviceDetails();
},
child: Text("Device Details",
style: TextStyle(color: Colors.black),),
),
deviceVersion.isNotEmpty && deviceName.isNotEmpty
&& identifier.isNotEmpty?
Column(
children: [
SizedBox(height: 30,),
Text("Device Name:- "+deviceName,style: TextStyle
(color: Colors.red,
fontWeight: FontWeight.bold)),
SizedBox(height: 30,),
Text("Device Version:- "+deviceVersion,style: TextStyle
(color: Colors.red,
fontWeight: FontWeight.bold)),
SizedBox(height: 30,),
Text("Device Identifier:- "+identifier,style: TextStyle
(color: Colors.red,
fontWeight: FontWeight.bold)),
SizedBox(height: 30,),
],
): Container(),
],
),
),
);
}
}

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying up the How To Get Unique Device Details In Flutter? in your flutter projectsWe will show you what the Introduction is?. Make a demo program for working Device Details and show when the user tap on the raised button, the unique device Andriod/Ios information like device name, version, identifier, etc shown on your screen using the device_info package in your flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.

find the source code of the Flutter Device Details Demo:

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


From Our Parent Company Aeologic

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

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

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

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

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


Feedback In Flutter

Getting user feedback is fundamental to further develop your Flutter application. The simpler you make this process the more feedback you will get.

This blog will explore Feedback In Flutter. We will learn how to execute a demo program. We will show how users submit feedback using the feedback package and also how users send feedback via emails using the flutter_email_sender package in your Flutter applications.

For Feedback:

feedback | Flutter package
A Flutter package for getting better feedback. It allows the user to give interactive feedback directly in the app.pub.dev

For Send Emails:

flutter_email_sender | Flutter package
Allows to send emails from flutter using native platform functionality.pub.dev

For path_provider:

path_provider | Flutter package
Flutter plugin for getting commonly used locations on host platform file systems, such as the temp and app data…pub.dev

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


Table Of Contents::

Introduction

Implementation

Code Implement

Code File

Conclusion



Introduction:

The below demo video shows how to get users to submit feedback and how to send feedback via emails in Flutter. How these functions will work using the flutter_email_sender package and feedback package in your Flutter applications. You can see that the entire application will turn into a dialog, this is the very justification for why the BetterFeedback widget ought to be the root widget. Inside the feedback dialog, the user can explore the application, draw the application, and add a description. It will be shown on your device.

Demo Module::


Implementation:

Add dependencies to pubspec — yaml file.

dependencies:
flutter:
sdk: flutter
feedback: ^3.1.0
flutter_email_sender: ^6.0.3
path_provider: ^2.1.4

Step 2: Import

import 'package:feedback/feedback.dart';
import 'package:flutter_email_sender/flutter_email_sender.dart';
import 'package:path_provider/path_provider.dart';

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

Step 4: We must also add the following intent to allow our application to send emails on Android. This can be done inside the android\app\src\main\AndroidManifest.xml file.

<queries>
<intent>
<action android:name="android.intent.action.SENDTO" />
<data android:scheme="mailto" />
</intent>
</queries>

How to implement code in dart file :

You need to implement it in your code respectively:

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

In this code snippet, we start by wrapping the entire application with the BetterFeedback widget. This is required because this widget ought to be the root of the widget tree. In particular, it ought to be over any Navigator widget, including the navigator given by the MaterialApp widget.

void main() => runApp(const BetterFeedback(child: MyApp()));

In the main. dart file, we will make another HomePage() class. In this class, we made another function called _writeScreenshotToStorage to briefly save the screen capture in the user’s storage. We want to do this so it tends to be utilized as an email attachment. Inside the callback of the show function of the BetterFeedback widget, we call the send function of the FlutterEmailSender.

Future<String> _writeScreenshotToStorage(Uint8List screenshot) async {
final directory = await getTemporaryDirectory();
final filePath = '${directory.path}/feedback.png';
final file = File(filePath);

await file.writeAsBytes(screenshot);

return filePath;
}

Now, we will create an ElevatedButton() method. In this method, we can call the accompanying function BetterFeedback.of(context).show open the feedback modal. This function takes an Email instance. For this situation, we added the accompanying ascribes to the Email instance, the attachmentPaths which takes our new function to save the screen capture.

ElevatedButton(
onPressed: () => BetterFeedback.of(context).show(
(UserFeedback feedback) async => FlutterEmailSender.send(
Email(
attachmentPaths: [
await _writeScreenshotToStorage(feedback.screenshot),
],
body: feedback.text,
recipients: ['user@gmail.com'],
subject:
feedback.text.split(' ').take(7).toList().join(' '),
),
),
),
child: const Text('Give Feedback'),
),

We set the body to our feedback description. We have added the beneficiaries which will be the email of the developer and we have added the subject which will be the initial 7 expressions of the feedback message.

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

Code File:

import 'dart:io';

import 'package:feedback/feedback.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_email_sender/flutter_email_sender.dart';
import 'package:flutter_feedback_demo/splash_screen.dart';
import 'package:path_provider/path_provider.dart';

void main() => runApp(const BetterFeedback(child: MyApp()));

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

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

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

Future<String> _writeScreenshotToStorage(Uint8List screenshot) async {
final directory = await getTemporaryDirectory();
final filePath = '${directory.path}/feedback.png';
final file = File(filePath);

await file.writeAsBytes(screenshot);

return filePath;
}

@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: Scaffold(
appBar: AppBar(
automaticallyImplyLeading: false,
title: const Text("Flutter Feedback Demo"),
backgroundColor: Colors.teal.shade100,
centerTitle: true,
),
body: Center(
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisAlignment: MainAxisAlignment.center,
children: [
Center(
child: Image.asset(
"assets/logo.png",
height: 100,
)),
const SizedBox(
height: 50,
),
ElevatedButton(
onPressed: () => BetterFeedback.of(context).show(
(UserFeedback feedback) async => FlutterEmailSender.send(
Email(
attachmentPaths: [
await _writeScreenshotToStorage(feedback.screenshot),
],
body: feedback.text,
recipients: ['user@gmail.com'],
subject:
feedback.text.split(' ').take(7).toList().join(' '),
),
),
),
child: const Text('Give Feedback'),
),
],
),
),
),
);
}
}

Conclusion:

In the article, I have explained the Feedback in a flutter; you can modify this code according to your choice. This was a small introduction to Send Feedback 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 Feedback in your Flutter projects. We will show you what the Introduction is. Make a demo program for working on how to get users to submit feedback and how to send feedback via emails Using the feedback package and flutter_email_sender package in your Flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


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


From Our Parent Company Aeologic

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

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

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

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

Related: SMS Using Twilio In Flutter

Related: Using SharedPreferences in Flutter

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


Story View In Flutter

In the present fast market, a few social channels have been out and out blasting and are the hot talk among individuals of all age gatherings. Stroll through the digital environment and you will notice new online media applications like Instagram standing hot as fire in the year and past.

At the point when you hear the term web-based media application, possibly applications like Facebook, Instagram, Twitter, or Linkedin come into view. Yet, have you at any point considered how to show a story on an online media application like Instagram?. Online media applications are an open gathering for you to associate with individuals from the whole way across the world with a simple UI.

In this blog, we will explore the Story View In Flutter. We will implement a story view demo program and how to create a story like WhatsApp using the story_view package in your flutter applications.

story_view | Flutter Package
Run this command: With Flutter: $ flutter pub add story_view This will add a line like this to your package’s…pub. dev

Table Of Contents::

Flutter Story View

Features

Properties

Implementation

Code Implement

Code File

Conclusion



Flutter Story View:

Story View Flutter Library Widget is helpful for the Flutter developer, By utilizing this library you can show Social media stories pages very much like WhatsApp Status Story or Instagram Status Story View. Can likewise be utilized inline/inside ListView or Column actually like the Google News application. Accompanies gestures to pause, forward, and go to the back page.

Demo Module :

This demo video shows how to create a story view in a flutter. It shows how the story view will work using the story_view package in your flutter applications. It displays your story like text, images, video, etc. Also, the user will forward, previous, and gesture to pause the stories. It will be shown on your device.

Features:

There are some features of Story View are:

  • > Simple Text Status story.
  • > Images, GIF Images Stories, and Video Stories( with caching enabled).
  • Gesture for Previous, Next, and Pause the Story.
  • Caption for each story item.
  • > An animated Progress indicator on top of every story view.

Properties:

There are some properties of Story View are:

  • controller: This property is used to controls the playback of the stories.
  • > onComplete: This property is used to the callback for when a full cycle of the story is shown. This will be called each time the full story completes when the repeat is set to true.
  • > storyItems: This property was not null and pages to display.
  • > onVerticalSwipeComplete: This property is used to the callback for when a vertical swipe gesture is detected. If you do not want to listen to such an event, do not provide it.
  • > onStoryShow: This property is used to the callback for when a story is currently being shown.
  • > progressPosition: This property is used where the progress indicator should be placed.

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:
flutter:
sdk: flutter
story_view:

Step 2: Import

import 'package:story_view/story_view.dart';

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

How to implement code in dart file :

You need to implement it in your code respectively:

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

In this screen, we will create a UI like WhatsApp. We will add a container widget. Inside, we will add network image, text, and onTap function wrap to the ListTile. In this function, we will navigate to StoryPageView() class.

Container(
height: 80,
padding: const EdgeInsets.all(8.0),
color: textfieldColor,
child: ListView(
children: <Widget>[
ListTile(
leading: CircleAvatar(
radius: 30,
backgroundImage: NetworkImage(
"https://images.unsplash.com/photo-1581803118522-7b72a50f7e9f?ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8bWFufGVufDB8fDB8fA%3D%3D&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60"),
),
title: Text(
"Logan Veawer",
style: TextStyle(fontWeight: FontWeight.bold,color: white ),
),
subtitle: Text("Today, 20:16 PM",style: TextStyle(color:white.withOpacity(0.5)),),
onTap: () => Navigator.push(
context,
MaterialPageRoute(
builder: (context) => StoryPageView())),
),
],
),
),

When the user presses the container then they will be shown a story page. We will deeply discuss the below code. When we run the application, we ought to get the screen’s output like the underneath screen capture.

Status Screen

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

First, we will create a final _controller that is equal to the StoryController().

final _controller = StoryController();

We will create a List of storyItems. First, we will add StoryItem.text means add only simple text status with the different background colors. Second, we will add StoryItem.pageImage means to add a URL of an image with the controller to control the story. Last, we will add the URL of the gif video with the controller and image fit.

final List<StoryItem> storyItems = [
StoryItem.text(title: '''“When you talk, you are only repeating something you know.
But if you listen, you may learn something new.”
– Dalai Lama''',
backgroundColor: Colors.blueGrey),
StoryItem.pageImage(
url:
"https://images.unsplash.com/photo-1553531384-cc64ac80f931?ixid=MnwxMjA3fDF8MHxzZWFyY2h8MXx8bW91bnRhaW58ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60",
controller: controller),
StoryItem.pageImage(
url:
"https://wp-modula.com/wp-content/uploads/2018/12/gifgif.gif",
controller: controller,
imageFit: BoxFit.contain),
];

We will return a Material() method. In this method, we will add StoryView(). Inside, we will add a list of storyItemscontrollerinline means if you would like to display the story as full-page, then set this to `false`. But in case you would display this as parts of a page like a ListView or Column then set this to true. We will add repeat means the user should the story be repeated forever then true otherwise, false.

return Material(
child: StoryView(
storyItems: storyItems,
controller: controller,
inline: false,
repeat: true,
),
);

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

Story View Page

Code File:

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

class StoryPageView extends StatefulWidget {
@override
_StoryPageViewState createState() => _StoryPageViewState();
}

class _StoryPageViewState extends State<StoryPageView> {
final controller = StoryController();

@override
Widget build(BuildContext context) {
final List<StoryItem> storyItems = [
StoryItem.text(title: '''“When you talk, you are only repeating something you know.
But if you listen, you may learn something new.”
– Dalai Lama''',
backgroundColor: Colors.blueGrey),
StoryItem.pageImage(
url:
"https://images.unsplash.com/photo-1553531384-cc64ac80f931?ixid=MnwxMjA3fDF8MHxzZWFyY2h8MXx8bW91bnRhaW58ZW58MHx8MHx8&ixlib=rb-1.2.1&auto=format&fit=crop&w=500&q=60",
controller: controller),
StoryItem.pageImage(
url:
"https://wp-modula.com/wp-content/uploads/2018/12/gifgif.gif",
controller: controller,
imageFit: BoxFit.contain),
];
return Material(
child: StoryView(
storyItems: storyItems,
controller: controller,
inline: false,
repeat: true,
),
);
}
}

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying up the Story View in your flutter projectsWe will show you what the Story View is?. Show some properties and features of the Story View widget. Make a demo program for working Story View and It displays your story like text, images, video, etc. Also, the user will forward, previous, and gesture to pause the stories using the story_view package in your flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.

find the source code of the FlutterStory View Demo:

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


From Our Parent Company Aeologic

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

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

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

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

Related: SMS Using Twilio In Flutter

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