Google search engine
Home Blog Page 24

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.


Explore AnimatedOpacity In Flutter

0

Eliminating a widget in Flutter is truly straightforward and simple. You simply need to revamp the tree without it. However, imagine a scenario where you need the widget to vanish yet at the same time occupy a space on the screen with the goal that it doesn’t disturb the remainder of the format. Well to settle this, you can attempt the AnimatedOpacity.

AnimatedOpacity class — widgets library — Dart API
API docs for the
AnimatedOpacity class from the widgets library, for the Dart programming language.api.flutter.dev

In this blog, we will Explore AnimatedOpacity In Flutter. We will see how to implement a demo program of the animated opacity with some properties and how to create it in your flutter applications.

Table Of Contents::

AnimatedOpacity

Properties

Code Implementation

Code File

Conclusion



AnimatedOpacity:

The AnimatedOpacity makes its child mostly transparent. This class colors its child into a middle buffer and afterward consolidates the child once again into the scene mostly transparent. For values of opacity other than 0.0 and 1.0, this class is moderately costly as it needs shading the child into a halfway support. For the value 0.0, the child is just not colored by any means. For the value 1.0, the child is colored without a moderate buffer.

Demo Module :

This demo video shows how to create animated opacity in a flutter. It shows how the animated opacity will work using the AnimatedOpacity class in your flutter applications. Basically, Opacity shows the disappear or presence of objects. In many situations, it can take a value from 1.0 to0.0 .1.0 methods full perceivability of the object and 0.0 means zero ability to see. Users can utilize any value in the middle of them for your ideal impact of opacity. It will be shown on your device.

Properties:

There ara some properties of AnimatedOpacity are:

  • key: This property is used to controls how one widget replaces another widget in the tree.
  • child: This property is the widget below this widget in the tree.
  • opacity: This property is used to the fraction to scale the child’s alpha value. An opacity of 1.0 is fully opaque. An opacity of 0.0 is fully transparent i.e., invisible. The opacity must not be null.
  • > curve: This property is a collection of common animation and used to adjust the rate of change of animation over time, allowing them to speed up and slow down, rather than moving at a constant rate.
  • > duration: This property represents a difference from one point in time to another. The duration may be “negative” if the difference is from a later time to an earlier.

Implementation:

Step 1: Add the assets

Add assets to pubspec — yaml file.

assets:
- assets/

Step 2: 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 opacity_demo.dart inside the lib folder.

First, we will create two variables. The first one is _opacity is equal to zero and the second one is _width is 230.

var _opacity = 0.0;
var _width = 230.0;

In the body part, we will create a Container widget. Inside the container, we will add alignment was center, height from mediaquery, and add the variable of width. We will add decoration with a border-radius that is circular and add color. It’s a child, we will add a Row widget. In this widget, we will add an image and text.

Container(
alignment: Alignment.center,
height: MediaQuery.of(context).size.height *0.08,
width: _width,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20.0),
color: Colors.cyan[400],
),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Image.asset("assets/devs.jpg",
scale: 10,
fit: BoxFit.contain,
),
Padding(
padding: const EdgeInsets.only(right:30.0),
child: Text(
'Flutter Devs',
style: TextStyle(color: Colors.white,
fontSize: 20.0)
,
),
),
],
),
),

Now let’s wrap the Row with an AnimatedOpacity widget and add the required properties to the widget.

In the AnimatedOpacity(), we will add duration for milliseconds. Users can choose seconds, microseconds, minutes, hours, and days for a long animation. We will add a curve that was bounceIn means an oscillating curve that first grows and then shrinks in magnitude. We will add variable _opacity on the opacity property.

AnimatedOpacity(
duration: Duration(milliseconds: 700),
curve: Curves.bounceIn,
opacity: _opacity,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Image.asset("assets/devs.jpg",
scale: 10,
fit: BoxFit.contain,
),
Padding(
padding: const EdgeInsets.only(right:30.0),
child: Text(
'Flutter Devs',
style: TextStyle(color: Colors.white,
fontSize: 20.0)
,
),
),
],
),
),

Now, we wrap the whole code to GestureDetector() method. In this method, we will add onTap. On onTap, we will add setState() function. In this function, if _opacity is already 0.0 then make it 1.0 otherwise, it should go reverse to 0.0 . Simple toggle operation.

GestureDetector(
onTap: () {
setState(() {
_opacity = _opacity == 0.0 ? 1 : 0.0;
});
},
),

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

Output

Code File:

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

class OpacityDemo extends StatefulWidget {
@override
OpacityDemoState createState() => OpacityDemoState();
}

class OpacityDemoState extends State<OpacityDemo> {

var _opacity = 0.0;
var _width = 230.0;


@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Color(0xffffffff),
appBar: AppBar(
backgroundColor: Colors.cyan[300],
title: Text("Flutter AnimatedOpacity Demo"),
automaticallyImplyLeading: false,
),
body: Center(
child: GestureDetector(
onTap: () {
setState(() {
_opacity = _opacity == 0.0 ? 1 : 0.0;
});
},
child: Container(
alignment: Alignment.center,
height: MediaQuery.of(context).size.height *0.08,
width: _width,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20.0),
color: Colors.cyan[400],
),
child: AnimatedOpacity(
duration: Duration(milliseconds: 700),
curve: Curves.bounceIn,
opacity: _opacity,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Image.asset("assets/devs.jpg",
scale: 10,
fit: BoxFit.contain,
),
Padding(
padding: const EdgeInsets.only(right:30.0),
child: Text(
'Flutter Devs',
style: TextStyle(color: Colors.white,
fontSize: 20.0)
,
),
),
],
),
),
),
),
),
);
}
}

Conclusion:

In the article, I have explained the AnimatedOpacity of the basic structure in a flutter; you can modify this code according to your choice. This was a small introduction to AnimatedOpacity 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 AnimatedOpacity in your flutter projectsWe will show you what the AnimatedOpacity is?. Some AnimatedOpacity properties make a demo program for working AnimatedOpacity and show that when the user taps the container then, the text will be shown with the animated effect. It can take a value from 1.0 to0.0 .1.0 methods full perceivability of the object and 0.0 means zero ability to see. Users can utilize any value in the middle of them for your ideal impact of opacity using the AnimatedOpacity 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 Opacity Demo:

flutter-devs/flutter_animated_opacity_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: Explore AnimatedSize In Flutter

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


Custom Rolling Switch In Flutter

switch is a two-state UI component used to flip between ON (Checked) or OFF (Unchecked) states. Ordinarily, it is a button with a thumb slider where the user can haul back and forth to pick an alternative as ON or OFF. Its working is like the house power switches.

In this article, we will explore the Custom Rolling Switch In Flutter. We will implement a custom rolling switch demo program with attractive animation and some properties using the lite_rolling_switch package in your flutter applications.

lite_rolling_switch | Flutter Package
Full customizable rolling switch widget for flutter apps based on Pedro Massango’s ‘crazy switch widget…pub. dev

Table Of Contents::

Introduction

Properties

Implementation

Code Implement

Code File

Conclusion



Introduction:

In Flutter, a switch is a widget used to choose between two alternatives, either ON or OFF. It doesn’t keep up the actual state. To keep up the states, it will call the onChanged property. Assuming the worth return by this property is true, the switch is ON and false when it is OFF. At the point when this property is invalid, the switch widget is debilitated.

Custom Rolling Switch button with alluring animation made to permit you to modify colors, symbols, and other restorative substances. Deal with the widget states similarly you do with the traditional material’s switch widget.

Demo Module :

This demo video shows how to create a custom rolling switch in a flutter. It shows how the custom rolling switch will work using the lite_rolling_switch package in your flutter applications. It shows toggle interaction where the user presses the button then, the switch will be rolling to another side with animation effect and the icons and text will be changed when the switch is rolling. It will be shown on your device.

Properties:

There are some properties of LiteRollingSwitch are:

  • > onChanged: This property is called when the user toggles the switch on or off.
  • > value: This property is used to determines whether this switch is on or off.
  • > animationDuration: This property is used how long an animation should take to complete one cycle.
  • > colorOn: This property is used to show color when the switch is On.
  • > colorOff: This property is used to show color when the switch is Off.

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:
flutter:
sdk: flutter
lite_rolling_switch:

Step 2: Import

import 'package:lite_rolling_switch/lite_rolling_switch.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 demo_screen.dart inside the lib folder.

In the body part, we will add the Center() widget. Inside the widget, we will add a Column widget. In this widget, we will add the mainAxisAlignment was center. Inside, we will add text with style. We will add padding and on its child add LiteRollingSwitch() widget for custom.

Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("Do you like Flutter?",style: TextStyle(
fontSize: 22,
fontWeight: FontWeight.bold
),
),

Padding(
padding: EdgeInsets.only(top: 20),
child: LiteRollingSwitch(
value: true,
textOn: 'Yes',
textOff: 'No',
colorOn: Colors.cyan,
colorOff: Colors.red[400],
iconOn: Icons.check,
iconOff: Icons.power_settings_new,
animationDuration: Duration(milliseconds: 800),
onChanged: (bool state) {
print('turned ${(state) ? 'yes' : 'no'}');
},
),
)
],
),
),

Inside, we will add value was true means which determines whether this switch is on or offWe will add textOn was the string ‘Yes’ means when the switch is On then the text will be shown on the button and when textOff was the string ‘No’ means when the switch is Off then the text will be shown on the button. We will add colorOn means when the switch is On then the color will be shown on the button and when colorOff means when the switch is Off then the color will be shown on the button. We will add animationDuration means to delay the start of the animation and add onChanged means when the user toggles the switch on or off. When we run the application, we ought to get the screen’s output like the underneath screen capture.

Final Output

Code File:

import 'dart:ui';

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

class DemoScreen extends StatefulWidget {


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

class _DemoScreenState extends State<DemoScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.teal[50],
appBar: AppBar(
automaticallyImplyLeading: false,
backgroundColor: Colors.black,
title: Text('Flutter Custom Rolling Switch'),
),
body: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
Text("Do you like Flutter?",style: TextStyle(
fontSize: 22,
fontWeight: FontWeight.bold
),
),

Padding(
padding: EdgeInsets.only(top: 20),
child: LiteRollingSwitch(
value: true,
textOn: 'Yes',
textOff: 'No',
colorOn: Colors.cyan,
colorOff: Colors.red[400],
iconOn: Icons.check,
iconOff: Icons.power_settings_new,
animationDuration: Duration(milliseconds: 800),
onChanged: (bool state) {
print('turned ${(state) ? 'yes' : 'no'}');
},
),
)
],
),
),
);
}
}

Conclusion:

In the article, I have explained the Custom Rolling Switch of the basic structure in a flutter; you can modify this code according to your choice. This was a small introduction to Custom Rolling Switch 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 Custom Rolling Switch in your flutter projectsWe will show you what the introduction is?. Show some properties, make a demo program for working Custom Rolling Switch and show toggle interaction where the user presses the button then, the switch will be rolling to another side with animation effect and the icons and text will be changed when the switch is rolling using the lite_rolling_switch 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 Custom Rolling Switch Demo:

flutter-devs/flutter_custom_rolling_switch_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: Custom Dialog In Flutter

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


SelectableText Widget In Flutter

0

At times you might need to make the Text content of your mobile selectable to utilize functionalities like a copy. On the off chance that you need to show text in Flutter, the normal route is by utilizing a Text widget. Be that as it may, it doesn’t permit the user to choose the text. If you need the user to have the option to select the text, you can utilize Flutter’s SelectableText widget.

In this blog, we will explore the SelectableText Widget In Flutter. We will see how to implement a demo program of the selectable text widget and show you how to utilize that widget to copy/select the text, making a text selectable is really simple in Flutter, you simply need to utilize the SelectableText widget in your flutter applications.

SelectableText class – material library – Dart API
A run of selectable text with a single style. The SelectableText widget displays a string of text with a single style…master-api. flutter.dev

Table Of Contents::

SelectableText Widget

Properties

Code Implement

Code File

Conclusion



SelectableText Widget:

The SelectableText widget shows a string of text with a solitary style. The string may break across various lines or may all be shown on a similar line contingent upon the design imperatives. To utilize SelectableText, there is just one required boundary which is the text to be shown was String.

SelectableText Widget in Flutter allows the user to Select/Copy the content on the UI. The typical Text Widget in Flutter won’t permit a copy/select element by double-tapping on the content, we can either select/copy the content. To take care of this issue, the Flutter discharge came out with the SelectableText Widget.

For more info on SelectableText Widget ,Watch this video By Flutter :

Below demo video shows how to create a selectable text in a flutter. It shows how the selectable text widget will work using the SelectableText Widget in your flutter applications. It shows two buttons on the center screen. When the user taps on these buttons, it will show allow the user to copy/select a feature by double-tapping on the text, we can either select/copy the text. It will be shown on your device.

Demo Module :


Properties:

There are some properties of the SelectableText widget are:

  • > data: This property is a significant property where the data to appear as a feature of the SelectableText must appear. The text to be shown.
  • > onTap: This property is utilized for the callback function that gets terminated at whatever point somebody taps on the Text of the SelectableText. Of course, the tapping opens the select all/copy choice. On the off chance that you need to perform different exercises, make a point to supersede them here.
  • > textSpan: This property is utilized as a component of the SelectableText.rich() widget. This allows you to pick the TextSpan which can hold various texts on the SelectableText widget.
  • > autofocus: This property is used whether it should focus itself if nothing else is already focused. Defaults to false.
  • > maxLines: This property is used for the maximum number of lines for the text to span, wrapping if necessary.
  • > toolbarOptions: This property is used to create a toolbar configuration with given options. All options default to false if they are not explicitly set.
  • > enableInteractiveSelection: This property is used to Whether to select text and show the copy/paste/cut menu when long-pressed. Defaults to true.

How to implement code in dart file :

You need to implement it in your code respectively:

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

We will make two buttons on this home page screen, and each button will show SelectableText Widget, and we will show the deeply below detail. When we run the application, we ought to get the screen’s output like the underneath screen capture.

Home Screen

We will deeply define below are the two different uses of the SelectableText class and the resulting output.

SelectableText Basic:

In the body part, we will add the center widget. In this widget, we will add SelectableText() method. Inside this method, we will add text, toolbarOptions. In these options, when selection is active, it shows ‘Copy’ and ‘Select all’ options. You can utilize the toolbarOptions property to pass an instance of ToolbarOptions. The constructor of ToolbarOptions has all values are copied, cut, paste, and selectAll set to false by default. You need to set every option to true on the off chance that you need it to show up on the toolbar. Be that as it may, cut and paste will not be showed regardless of whether you set it to true.

Center(
child: SelectableText(
"Flutter Tutorial by Flutter Dev's.com",
style: TextStyle(color: Colors.blue,
fontWeight: FontWeight.bold,
fontSize: 45
),
textAlign: TextAlign.center,
onTap: () => print('Tapped'),
toolbarOptions: ToolbarOptions(copy: true, selectAll: true,),
showCursor: true,
cursorWidth: 2,
cursorColor: Colors.red,
cursorRadius: Radius.circular(5),

),
),

We will add the showCursor option true, cursor width, color, and radius. When we run the application, we ought to get the screen’s output like the underneath screen capture.

SelectableText Basic

SelectableText RichText:

In the body part, we will add the center widget. In this widget, we will add SelectableText.rich() method. In this method, that you need the content to have various formats, utilizing RichText is the normal methodology in Flutter. It’s likewise conceivable to have a selectable RichText by utilizing SelectableText.rich named constructor. It acknowledges an TextSpan as the first and the solitary required boundary rather than a String. Different boundaries, which are optional, are the same equivalent to the main constructor.

Center(
child: SelectableText.rich(
TextSpan(
children: <TextSpan>[
TextSpan(text: 'Flutter', style: TextStyle(color: Colors.blue)),
TextSpan(text: 'Devs', style: TextStyle(color: Colors.black)),
TextSpan(text: '.com', style: TextStyle(color: Colors.red)),
],
),
style: TextStyle(
fontWeight: FontWeight.bold,
fontSize: 48),
textAlign: TextAlign.center,
onTap: () => print('Tapped'),
toolbarOptions: ToolbarOptions(copy: true, selectAll: false),
showCursor: true,
cursorWidth: 2,
cursorColor: Colors.black,
cursorRadius: Radius.circular(5),
),
)

We will add toolbarOptons, which shows ‘Copy’ was true and ‘Select all’ was false options. When we run the application, we ought to get the screen’s output like the underneath screen capture.

SelectableText RichText

Code File:

import 'package:flutter/material.dart';
import 'package:flutter_selectabletext_widget/selectable_text_rich_screen.dart';
import 'package:flutter_selectabletext_widget/selectable_text_screen.dart';



class HomePageScreen extends StatefulWidget {
@override
_HomePageScreenState createState() => _HomePageScreenState();
}

class _HomePageScreenState extends State<HomePageScreen> {
@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: Colors.blueGrey[100],
appBar: AppBar(
title: Text("Flutter SelectableText Widget Demo"),
automaticallyImplyLeading: false,
centerTitle: true,
),
body: Center(
child: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.stretch,
children: <Widget>[

RaisedButton(
child: Text('Selectable Text',style: TextStyle(color: Colors.black),),
color: Colors.green[100],
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => SelectableTextScreen()));
},
shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(20))),
padding: EdgeInsets.all(13),
),
SizedBox(height: 8,),
RaisedButton(
child: Text('Selectable Text Rich',style: TextStyle(color: Colors.black),),
color: Colors.green[100],
onPressed: () {
Navigator.of(context).push(
MaterialPageRoute(builder: (context) => SelectableTextRichScreen()));
},
shape: RoundedRectangleBorder(borderRadius: BorderRadius.all(Radius.circular(20))),
padding: EdgeInsets.all(13),

),
SizedBox(height: 8,),

],
),
)
), //center
);
}
}

Conclusion:

In the article, I have explained the basic structure of the SelectableText Widget in a flutter; you can modify this code according to your choice. This was a small introduction to SelectableText Widget 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 SelectableText Widget in your flutter projects. We will show you what the SelectableText Widget is?, some properties using in SelectableText Widget, and make a demo program for working SelectableText Widget and show you how to use that widget to copy/select the text, making a text selectable is pretty easy in Flutter using the SelectableText Widget widget in your flutter applications, So please try it.

❤ ❤ Thanks for reading this article ❤❤


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

Clap 👏 If this article helps you.

find the source code of the Flutter SelectableText Widget Demo:

flutter-devs/flutter_selectabletext_widget_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.