Google search engine
Home Blog Page 12

Octo Image In Flutter

OctoImage is a multifunctional flutter picture widget that is a picture library for showing placeholders, error widgets, and changing your picture.

In this blog, we will explore Octo Image In Flutter. We will also implement a demo program, and learn how to use octo images using the octo_image package in your flutter applications.

octo_image | Flutter Package
An image library for showing placeholders, error widgets, and transforming your image. Recommended using with…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

How to use

Implementation

Code Implement

Code File

Conclusion



Introduction:

The OctoImage widget in flutter requires an ImageProvider to show pictures in an application. The pictures in the OctoImage widget can be provided with a progress indicator and a placeholder for loading the Picture in it.

An OctoImage widget utilizes the Octosets which are only a mix of predefined placeholders, imagebuilders, and error widgets.

Demo Module ::

This demo video shows how to use octo images in a flutter and shows how an Octo Image will work using the octo_image package in your flutter applications. We will show a user different types of images with blur, placeholder, and progress indicators will be shown on your devices.

OctoImage Uses:

There are two ways to use the OctoImage widget as shown below:

  • > Using OctoImage:
OctoImage(
image: NetworkImage(
'YOUR IMAGE URL'),
placeholderBuilder: OctoPlaceholder.blurHash(
'PLACEHOLDER',
),
errorBuilder: OctoError.icon(color: Colors.red),
fit: BoxFit.cover,
);
  • > Using Octosets:
OctoImage.fromSet(
fit: BoxFit.cover,
image: NetworkImage(
'YOUR IMAGE URL',
),
octoSet: OctoSet.circleAvatar(
backgroundColor: Colors.red,
text: Text("Your Text"),
),
);

Implementation:

Step 1: Add the dependencies

Add dependencies to pubspec — yaml file.

dependencies:
flutter:
sdk: flutter
octo_image: ^1.0.2

Step 2: Import

import 'package:octo_image/octo_image.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:

We will create a class OctoImageDemo extend with StatelessWidget. We will add an appbar and body. In the body, we will add three widgets _image()_blurImage(), and _circleAvatarImage().

class OctoImageDemo extends StatelessWidget {
const OctoImageDemo({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter Octo Image Demo'),
backgroundColor: Colors.cyan,
automaticallyImplyLeading: false,
centerTitle: true,
),
body: ListView(
children: [
_image(),
const SizedBox(height: 10),
_blurImage(),
const SizedBox(height: 10),
_circleAvatarImage(),
],
),
);
}
}

First, we will define _image() widget are:

In this widget, we will return SizedBox with a height was 220 and its child OctoImage(). In this OctoImage, we will add an image, progressIndicatorBuilder, and errorBuilder. When the user runs the code first CircularProgressIndicator will run until the image shows.

Widget _image() {
return SizedBox(
height: 220,
child: OctoImage(
image: const NetworkImage(
'https://images.unsplash.com/photo-1516321318423-f06f85e504b3?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTZ8fHRlY2huaWNhbHxlbnwwfHwwfHw%3D&auto=format&fit=crop&w=400&q=60'),
progressIndicatorBuilder: (context, progress) {
double? value;
if (progress != null && progress.expectedTotalBytes != null) {
value =
progress.cumulativeBytesLoaded / progress.expectedTotalBytes!;
}
return CircularProgressIndicator(value: value);
},
errorBuilder: (context, error, stacktrace) => const Icon(Icons.error),
),
);
}

Now, we will define _blurImage() widget are:

In this widget, we will blur the image while it’s loading. We will return an AspectRatio was 268 / 173.

Widget _blurImage() {
return AspectRatio(
aspectRatio: 268 / 173,
child: OctoImage(
image: const NetworkImage(
'https://images.unsplash.com/photo-1619551964399-dad708b59b8b?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTR8fHRlY2huaWNhbHxlbnwwfHwwfHw%3D&auto=format&fit=crop&w=400&q=60'),
placeholderBuilder: OctoPlaceholder.blurHash(
'LEHV6nWB2yam9wo0adR*.7kCMdnj',
),
errorBuilder: OctoError.icon(color: Colors.red),
fit: BoxFit.cover,
),
);
}

Last, we will define _circleAvatarImage() widget are:

In this widget, we will create a circular avatar to which custom text can be added while it’s loading and can be used as follows.

Widget _circleAvatarImage() {
return SizedBox(
height: 220,
child: OctoImage.fromSet(
fit: BoxFit.cover,
image: const NetworkImage(
'https://images.unsplash.com/photo-1579445710183-f9a816f5da05?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8YXZlbmdlcnN8ZW58MHx8MHx8&auto=format&fit=crop&w=400&q=60',
),
octoSet: OctoSet.circleAvatar(
backgroundColor: Colors.red,
text: const Text("Flutter"),
),
),
);
}

Handling Errors:

A basic method for dealing with mistakes in the OctoImage Widget is to utilize the error widget. These are shown when the ImageProvider throws an error because the picture neglected to stack.

We can construct our custom widget, or we can likewise utilize the prebuild widgets:

OctoImage(
image: image,
errorBuilder: (context, error, stacktrace) =>
const Icon(Icons.error),
);


OctoImage(
image: image,
errorBuilder: OctoError.icon(),
),

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';
import 'package:flutter_octo_image_demo/splash_screen.dart';
import 'package:octo_image/octo_image.dart';

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

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

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

class OctoImageDemo extends StatelessWidget {
const OctoImageDemo({Key? key}) : super(key: key);

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter Octo Image Demo'),
backgroundColor: Colors.cyan,
automaticallyImplyLeading: false,
centerTitle: true,
),
body: ListView(
children: [
_image(),
const SizedBox(height: 10),
_blurImage(),
const SizedBox(height: 10),
_circleAvatarImage(),
],
),
);
}

Widget _image() {
return SizedBox(
height: 220,
child: OctoImage(
image: const NetworkImage(
'https://images.unsplash.com/photo-1516321318423-f06f85e504b3?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTZ8fHRlY2huaWNhbHxlbnwwfHwwfHw%3D&auto=format&fit=crop&w=400&q=60'),
progressIndicatorBuilder: (context, progress) {
double? value;
if (progress != null && progress.expectedTotalBytes != null) {
value =
progress.cumulativeBytesLoaded / progress.expectedTotalBytes!;
}
return CircularProgressIndicator(value: value);
},
errorBuilder: (context, error, stacktrace) => const Icon(Icons.error),
),
);
}

Widget _blurImage() {
return AspectRatio(
aspectRatio: 268 / 173,
child: OctoImage(
image: const NetworkImage(
'https://images.unsplash.com/photo-1619551964399-dad708b59b8b?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MTR8fHRlY2huaWNhbHxlbnwwfHwwfHw%3D&auto=format&fit=crop&w=400&q=60'),
placeholderBuilder: OctoPlaceholder.blurHash(
'LEHV6nWB2yam9wo0adR*.7kCMdnj',
),
errorBuilder: OctoError.icon(color: Colors.red),
fit: BoxFit.cover,
),
);
}

Widget _circleAvatarImage() {
return SizedBox(
height: 220,
child: OctoImage.fromSet(
fit: BoxFit.cover,
image: const NetworkImage(
'https://images.unsplash.com/photo-1579445710183-f9a816f5da05?ixlib=rb-4.0.3&ixid=MnwxMjA3fDB8MHxzZWFyY2h8MXx8YXZlbmdlcnN8ZW58MHx8MHx8&auto=format&fit=crop&w=400&q=60',
),
octoSet: OctoSet.circleAvatar(
backgroundColor: Colors.red,
text: const Text("Flutter"),
),
),
);
}
}

Conclusion:

In the article, I have explained Octo Image’s basic structure in a flutter; you can modify this code according to your choice. This was a small introduction to Octo Image 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 Octo Image in your flutter projectsWe will show you what the Introduction is. Make a demo program for working with Octo Image and you’ve learned how to use Octo Image using the octo_image package in your flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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

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


Custom Toast Message In Flutter

0

In flutter, no particular widget or function is accessible to show a toast message. We can utilize the snackbar widget rather than toast at the same time, we can’t change the place of the snackbar like toast. To add usefulness for showing toast messages to our flutter application we need to utilize FlutterToast dependency.

This blog will explore the Custom Toast Message In Flutter. We perceive how to execute a demo program. We will learn how to create custom toast messages using fluttertoast dependency with different properties in your flutter applications.

fluttertoast | Flutter Package
Toast Library for Flutter Now this toast library supports two kinds of toast messages one which requires BuildContext…pub.dev

Table Of Contents :

Introduction

Properties

Implementation

Code Implement

Code File

Conclusion



Introduction:

Toast is only a flash message in a flutter, which is utilized to show data to the client temporarily. It shows up at the lower part of the screen as default and disappears after a particular time.

For the most part, we will utilize a toast message to inform the user about the situation with the activity performed. For example, after presenting a registration form we can tell the user about the situation with the enlistment utilizing a toast message.

Demo Module :

The above demo video shows how to create a custom toast message in a flutter. It shows how the custom toast message will work using the fluttertoast package in your flutter applications. It shows when the user presses the button and then toast will display on your screen.

Properties:

Let’s customize the toast message utilizing various properties of FToast.ShowToast() method. These properties will assist in styling and situating the toast message.

  • > child — This property is used to take a widget as value. We will use this property to add a child widget which is a custom toast message.
  • > toastDuration — This property is used to take Duration as value. We will define how long we want the toast message to appear on the screen.
  • > gravity — This property is used to it takes constants of ToastGravity like BOTTOM_LEFT, BOTTOM_RIGHT, BOTTOM, etc.
  • > fadeDuration — This property is used to take an int as value. We will define how long the toast message should fade before appearing on the screen.
  • > positionedToastBuilder — This property is used to take a builder function as a value. If we want to position the toast message at the custom position on the screen other than the constant values of ToastGravity discussed above.

Implementation:

Add dependencies to pubspec — yaml file.

dependencies:
flutter:
sdk: flutter
fluttertoast: ^8.1.1

Step 2: Import

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

We have to declare an object of class FToast which is provided in the dependency.

FToast? fToast;

Now, we have to initialize the object with the current context in the initState() method.

@override
void initState() {
super.initState();
fToast = FToast();
fToast?.init(context);
}

In the body part, we will add a Column widget. In this widget, we will add CrossAxisAlignment as the center. Also, add an image and ElevatedButton with text and the onPressed method. In this method, we will add the showCustomToast() method.

Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const SizedBox(height: 50,),
Image.asset(
"assets/logo.png",
height: 300,
width: 350,
),
ElevatedButton(
child: const Text("Show Custom Toast Message"),
onPressed: () {
showCustomToast();
},
),
],
),

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

Output

Now we will deeply describe showCustomToast() method are:

We will create the showCustomToast() method. In this method, we will add a Widget toast and showToast.

showCustomToast() {
Widget toast = Container(
padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 12.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(25.0),
color: Colors.blueGrey,
),
child: const Text(
"This is a Custom Toast Message",
style: TextStyle(color: Colors.white),
),
);

fToast?.showToast(
child: toast,
toastDuration: const Duration(seconds: 3),
);
}

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';
import 'package:flutter_custom_toast_message_demo/splash_screen.dart';
import 'package:fluttertoast/fluttertoast.dart';

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

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

@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.teal,
),
home: const Splash(),
debugShowCheckedModeBanner: false,
);
}
}

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

@override
_MyHomePageState createState() {
return _MyHomePageState();
}
}

class _MyHomePageState extends State<MyHomePage> {
FToast? fToast;

@override
void initState() {
super.initState();
fToast = FToast();
fToast?.init(context);
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Flutter Custom Toast Message Demo"),
centerTitle: true,
automaticallyImplyLeading: false,
),
body: Container(
margin: const EdgeInsets.all(20),
alignment: Alignment.topCenter,
child: Column(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
const SizedBox(height: 50,),
Image.asset(
"assets/logo.png",
height: 300,
width: 350,
),
ElevatedButton(
child: const Text("Show Custom Toast Message"),
onPressed: () {
showCustomToast();
},
),
],
),
));
}

showCustomToast() {
Widget toast = Container(
padding: const EdgeInsets.symmetric(horizontal: 24.0, vertical: 12.0),
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(25.0),
color: Colors.blueGrey,
),
child: const Text(
"This is a Custom Toast Message",
style: TextStyle(color: Colors.white),
),
);

fToast?.showToast(
child: toast,
toastDuration: const Duration(seconds: 3),
);
}
}

Conclusion:

In the article, I have explained the Custom Toast Message basic structure in a flutter; you can modify this code according to your choice. This was a small introduction to Custom Toast Message 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 Custom Toast Message in your flutter projectsWe will show you what the Introduction is. Make a demo program for a working Custom Toast Message using the fluttertoast package in your flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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


Decorator Design Patterns For Dart & Flutter

0

Utilizing inheritance, we can statically broaden the usefulness of a Dart class. Yet, imagine a scenario in which we need more adaptability than that. We might need to add conduct to an object progressively, maybe as a user makes quality determinations.

The Decorator pattern can help! With this pattern, we can join a new way of behaving or properties to an object by enclosing it with an extraordinary decorator that shares the object’s interface.

This blog will explore Decorator Design Patterns for Dart & Flutter. We will perceive how to execute a demo program. Learn how to implement and use it in your flutter applications.

Table Of Contents::

Introduction

Decorator Pattern Example

Conclusion



Introduction:

The Decorator design is a method for expanding objects involving creation rather than inheritance, which is the methodology that works most normally in a Flutter application.

The patterns assist us with molding the connections between the objects and classes we make. These patterns are focused on how classes acquire from one another, how objects can be made out of different objects, and how objects and classes interrelate.

In this article, you’ll figure out how to assemble enormous, exhaustive frameworks from less complex, individual modules, and parts. The patterns help us in making adaptable, approximately coupled, interconnecting code modules to get done with complex responsibilities sensibly.

Decorator Pattern Example:

To exhibit the pattern, we’ll utilize color models, the exemplary workhorse of configuration design models. To begin with, we want to characterize a connection point for colors, and we’ll throw in a couple of sample color classes:

abstract class Color {
String paint();
}
class Red implements Color {
String paint() => "Red";
}
class Blue implements Color {
String paint() => "Blue";
}

Keep in mind, in Dart, there are no unequivocal connection points, however, every class exports its interaction for execution. We characterize the Color interface utilizing an abstract class with the goal that it can’t be straightforwardly launched. In this improved, model, the paint() technique will return a string properly to the color’s sort.

Since Red and Blue implement Color, they are expected to give execution the paint() technique. This implies client code can make factors of type Color that can be allotted to any color class.

With the color models set up, we can characterize a decorator interface and several example decorators:

abstract class ColorDecorator implements Color {
final Color color;
  ColorDecorator(this.color);
  String paint();
}
class GreenColorDecorator extends ColorDecorator {
GreenColorDecorator(Color color) : super(color);
@override
String paint() => "Green ${color.paint()}";
}
class BrownColorDecorator extends ColorDecorator {
BrownColorDecorator(Color color) : super(color);
@override
String paint() => "Brown ${color.paint()}";
}

Yet again we utilize an abstract class to characterize the point of interaction all color decorators ought to stick to. Moreover, ColorDecorator executes Color, so all classes that broaden ColorDecorator are connection points viable with color classes.

This is key because it implies we can start up a decorator, pass it a color, and afterward utilize the decorator like it were the color. That is the pith of the Decorator’s design.

Every decorator class inherits everything from ColorDecorator and overrides the unimplemented paint() strategy. It’s discretionary yet prescribed to incorporate the @override metatag while overriding acquired techniques.

Note that the color classes don’t override paint(); they should carry out paint(), yet they are not superseding an acquired technique when they do since they acquire nothing. Decorator constructors take a reference to the color they’ll design, and they give it to the abstract superclass’ constructor to be put away in the color property. The overridden draw() techniques in the decorator classes prepend their particular adornment onto the designed color’s string portrayal.

Here is an instance of utilizing the color decoration framework:

final red = Red();
print(red.paint());
final greenRed = GreenColorDecorator(red);
print(greenRed.paint());
final brownGreenColor= BrownColorDecorator(greenRed);
print(brownGreenColor.paint());

In the first place, we make a red and print the result from its paint() strategy, which will be the color’s name alone. To make a green red, we develop an example of GreenColorDecorator and passed it to the red. At the point when we draw the green red, we see that the red has been designed.

One of the qualities of the Decorator design is the capacity to apply however many decorators we wish to any object, so we can add a brown to the green red, bringing about a red with both variety enhancements.

Conclusion:

This blog will provide you with sufficient information on Trying up the Decorator Design Patterns for Dart & Flutter in your projectsYou can see that this pattern gives an adaptable method for adding qualities or conduct to an item at runtime, piecemeal, as an option in contrast to making new classes to cover each mix of characteristics an object might require.

❤ ❤ 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 you share what you’re working on using #FlutterDevs. We truly enjoy seeing how you use Flutter to build beautiful, interactive web experiences.


Select Item Of List In Flutter

0

In some cases, we need to choose more than one thing from the list and play out some action i.e delete the selected item and so forth.

This blog will explore the Select Item Of List In Flutter. We perceive how to execute a demo program. We will learn how to select an item from the list in your flutter applications.

Table Of Contents::

Introduction

Code Implement

Code File

Conclusion



Introduction:

The below demo video shows how to select the items of the list in a flutter and shows how a select item will work in your flutter applications. We will show the user long press the items, then the items will be selected or deselected. Also, the user selected/ de-selected all items with a single click. It will be shown on your devices.

Demo Module ::


Code Implement:

You need to implement it in your code respectively:

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

First of all, we need some data to make the app look like a real app and take some real scenarios. Create a data.dart file.

class MyData {
static List<Map> data = [
{
"id": 1,
"name": "Rahul",
"email": "rahul240@gamil.com",
"address": "120 kanpur India"
},
{
"id": 2,
"name": "Yogesh",
"email": "yogi@gamil.com",
"address": "1A/24 Delhi India"
},
{
"id": 3,
"name": "Rakhi",
"email": "rakhi@inc.com",
"address": "221 Bihar India"
},
{
"id": 4,
"name": "Thomas",
"email": "roy@yahoo.com",
"address": "406 Mumbai India"
},
{
"id": 5,
"name": "Manoj",
"email": "mnaoj24@aeo.com",
"address": "54 Noida Dadri"
},
{
"id": 6,
"name": "Mohit",
"email": "mohit5@gamil.com",
"address": "35 Greater Noida"
},
{
"id": 7,
"name": "Sadman",
"email": "khan6@gamil.com",
"address": "132 Pune India"
},
{
"id": 8,
"name": "Nadeem",
"email": "nawab7@gamil.com",
"address": "121 Lucknow India"
},
{
"id": 9,
"name": "Yashwant",
"email": "yash@gmail.com",
"address": "32 Delhi India"
},
{
"id": 10,
"name": "Prasad",
"email": "prasad@yahoo.com",
"address": "217 Mumbai India"
},
{
"id": 11,
"name": "Pragati",
"email": "pragati@tumblr.com",
"address": "3 Dehradun India"
},
{
"id": 12,
"name": "Imojean",
"email": "iwalbrookb@zdnet.com",
"address": "91904 Fieldstone Lane"
},
{
"id": 13,
"name": "Rochell",
"email": "rsharplesc@drupal.org",
"address": "46 Schmedeman Place"
},
{
"id": 14,
"name": "Fayina",
"email": "fwellwoodd@mapquest.com",
"address": "1 Anderson Street"
},
{
"id": 15,
"name": "Dilan",
"email": "dgethinge@wsj.com",
"address": "87297 High Crossing Alley"
},
{
"id": 16,
"name": "Berkie",
"email": "bmousbyf@si.edu",
"address": "5611 Colorado Drive"
},
{
"id": 17,
"name": "Aliza",
"email": "aabelsg@de.vu",
"address": "56 Dunning Way"
},
{
"id": 18,
"name": "Gene",
"email": "gernih@slashdot.org",
"address": "0479 Jay Court"
},
{
"id": 19,
"name": "Devland",
"email": "dlindbladi@geocities.jp",
"address": "0971 Johnson Terrace"
},
{
"id": 20,
"name": "Leigh",
"email": "larlidgej@xinhuanet.com",
"address": "430 Hanover Park"
},
{
"id": 21,
"name": "Annamaria",
"email": "agerreyk@jiathis.com",
"address": "03345 Larry Junction"
},
{
"id": 22,
"name": "Agace",
"email": "arubenczykl@meetup.com",
"address": "119 Stuart Alley"
},
{
"id": 23,
"name": "Ninette",
"email": "nhuglim@npr.org",
"address": "746 Calypso Plaza"
},
{
"id": 24,
"name": "Sosanna",
"email": "scopestaken@cloudflare.com",
"address": "81924 North Parkway"
},
{
"id": 25,
"name": "Millard",
"email": "mcullumo@jigsy.com",
"address": "6215 Hoepker Park"
},
];
}

The code will seem to be like the given snippet. Presently you go the data and now is the ideal time to render the data in the application and move towards the choice feature.

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

Now we will make the UI using the ListView.builder. The data will be loaded from the data. dart.

import 'package:flutter/material.dart';
import 'package:flutter_select_list_item_demo/data.dart';
class HomePage extends StatefulWidget {
@override
_HomePageState createState() => _HomePageState();
}
class _HomePageState extends State<HomePage> {
List<Map> staticData = MyData.data;
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter Select Item Of List Demo'),
automaticallyImplyLeading: false,
centerTitle: true,
backgroundColor: Colors.cyan,
),
body: ListView.builder(
itemBuilder: (builder, index) {
Map data = staticData[index];
selectedFlag[index] = selectedFlag[index] ?? false;
bool? isSelected = selectedFlag[index];

return ListTile(
onLongPress: () => onLongPress(isSelected!, index),
onTap: () => onTap(isSelected!, index),
title: Text("${data['name']}"),
subtitle: Text("${data['email']}"),
leading: _buildSelectIcon(isSelected!, data),
);
},
itemCount: staticData.length,
),
);
}
}

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

Output

Now will be added Selection Mode:

If I discuss myself, I will most likely utilize a long press. i.e When you long-press on the list item then it chooses the long-pressed thing and enables the determination mode.

On the off chance that anything is chosen from the list, the selection model is empowered.

We want a variable to flag the choice status of the item. To monitor the list of item determinations, we will utilize Map. The Map will store the unique id as the key and the boolean as the choice flag.

Adding Flag Variable for tracing selection Status:

Presently we want to follow which thing is chosen and which isn’t. To store this we want a variable of some sort. As we have a list of data so we likewise need a variable that can store the list of data.

import 'package:flutter/material.dart';
import 'package:flutter_select_list_item_demo/data.dart';

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

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

class _HomePageState extends State<HomePage> {
bool isSelectionMode = false;
List<Map> staticData = MyData.data;
Map<int, bool> selectedFlag = {};

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter Select Item Of List Demo'),
automaticallyImplyLeading: false,
centerTitle: true,
backgroundColor: Colors.cyan,
),
body: ListView.builder(
itemBuilder: (builder, index) {
Map data = staticData[index];
selectedFlag[index] = selectedFlag[index] ?? false;
bool? isSelected = selectedFlag[index];

return ListTile(
onLongPress: () => onLongPress(isSelected!, index),
onTap: () => onTap(isSelected!, index),
title: Text("${data['name']}"),
subtitle: Text("${data['email']}"),
leading: _buildSelectIcon(isSelected!, data),
);
},
itemCount: staticData.length,
),
);
}

void onTap(bool isSelected, int index) {
if (isSelectionMode) {
setState(() {
selectedFlag[index] = !isSelected;
isSelectionMode = selectedFlag.containsValue(true);
});
} else {
// Open Detail Page
}
}

void onLongPress(bool isSelected, int index) {
setState(() {
selectedFlag[index] = !isSelected;
isSelectionMode = selectedFlag.containsValue(true);
});
}

Widget _buildSelectIcon(bool isSelected, Map data) {
if (isSelectionMode) {
return Icon(
isSelected ? Icons.check_box : Icons.check_box_outline_blank,
color: Theme.of(context).primaryColor,
);
} else {
return CircleAvatar(
child: Text('${data['id']}'),
);
}
}
}

We can utilize a list yet using a map will be better and more powerful here. We can have user_id as the key to map and value as a boolean. As the list thing has an id and it’s extraordinary so utilizing a map is the most ideal choice here.

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

Selected Output

Now Adding Select All Button:

Presently we will add the select all button so we can choose every one of the things on the list utilizing one tap/click. This is vital in the creation application and this feature makes life simpler when there is an extremely extensive list.

Add this line of code to the Scaffold

floatingActionButton: _buildSelectAllButton(),

The button will be apparent when the selectionMode is empowered. The floating Button icon button changed based on the item chosen.

Widget? _buildSelectAllButton() {
bool isFalseAvailable = selectedFlag.containsValue(false);
if (isSelectionMode) {
return FloatingActionButton(
backgroundColor: Colors.cyan,
onPressed: _selectAll,
child: Icon(
isFalseAvailable ? Icons.done_all : Icons.remove_done,
),
);
} else {
return null;
}
}

void _selectAll() {
bool isFalseAvailable = selectedFlag.containsValue(false);
selectedFlag.updateAll((key, value) => isFalseAvailable);
setState(() {
isSelectionMode = selectedFlag.containsValue(true);
});
}

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

Output

Code File:

import 'package:flutter/material.dart';
import 'package:flutter_select_list_item_demo/data.dart';

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

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

class _HomePageState extends State<HomePage> {
bool isSelectionMode = false;
List<Map> staticData = MyData.data;
Map<int, bool> selectedFlag = {};

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text('Flutter Select Item Of List Demo'),
automaticallyImplyLeading: false,
centerTitle: true,
backgroundColor: Colors.cyan,
),
body: ListView.builder(
itemBuilder: (builder, index) {
Map data = staticData[index];
selectedFlag[index] = selectedFlag[index] ?? false;
bool? isSelected = selectedFlag[index];

return ListTile(
onLongPress: () => onLongPress(isSelected!, index),
onTap: () => onTap(isSelected!, index),
title: Text("${data['name']}"),
subtitle: Text("${data['email']}"),
leading: _buildSelectIcon(isSelected!, data),
);
},
itemCount: staticData.length,
),
floatingActionButton: _buildSelectAllButton(),
);
}

void onTap(bool isSelected, int index) {
if (isSelectionMode) {
setState(() {
selectedFlag[index] = !isSelected;
isSelectionMode = selectedFlag.containsValue(true);
});
} else {
// Open Detail Page
}
}

void onLongPress(bool isSelected, int index) {
setState(() {
selectedFlag[index] = !isSelected;
isSelectionMode = selectedFlag.containsValue(true);
});
}

Widget _buildSelectIcon(bool isSelected, Map data) {
if (isSelectionMode) {
return Icon(
isSelected ? Icons.check_box : Icons.check_box_outline_blank,
color: Theme.of(context).primaryColor,
);
} else {
return CircleAvatar(
child: Text('${data['id']}'),
);
}
}

Widget? _buildSelectAllButton() {
bool isFalseAvailable = selectedFlag.containsValue(false);
if (isSelectionMode) {
return FloatingActionButton(
backgroundColor: Colors.cyan,
onPressed: _selectAll,
child: Icon(
isFalseAvailable ? Icons.done_all : Icons.remove_done,
),
);
} else {
return null;
}
}

void _selectAll() {
bool isFalseAvailable = selectedFlag.containsValue(false);
selectedFlag.updateAll((key, value) => isFalseAvailable);
setState(() {
isSelectionMode = selectedFlag.containsValue(true);
});
}
}

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying Select Items From the List in your flutter projectsWe will show you make a demo program for working with selecting an item from the list in your flutter applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

If I need to correct something? Let me know in the comments. I would love to improve.

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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

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


Explore Futures & Completers In Dart & Flutter

0

Even though Dart, with its helpful async/await syntax, can take a ton of the intricacy out of overseeing asynchronous calls, some of the time you want to cooperate with a more conventional callback library or a constant association that doesn’t work with prospects.

That is where completers come into the image. You can work on the API surface of a stateless callback library, similar to the one used to get to REST web APIs, by wrapping it with a future-based API. You can do likewise with stateful, relentless association APIs.

This blog will be Explore Futures & Completers In Dart & Flutter. We will perceive how to execute a demo program. Learn how to implement and use it in your flutter applications.

Table Of Contents::

Wrapping Callback library To Use Futures

Wrapping Persistent Connection To Use Futures

Conclusion



Wrapping Callback library To Use Futures:

A completer permits you to make and deal with a future. Whenever you’ve started up a completer, you can utilize it to restore a future to your APIs, and when an extended asynchronous call returns data or an error, you can finish that future, conveying the outcome.

To use completers, you need to import the dart:async core library. In the example, we’ve created a function, asyncQuery()that interacts with a fictional network call represented by getHttpData(). Our function will return a future initially, but it will resolve into string data at a later time.

To utilize completers, you want to import the dart: async core library. In the model, we’ve made a capability, asyncQuery() that cooperates with an imaginary network call addressed by getHttpData().

import 'dart:async';
Future<String> asyncQuery() {
final completer = Completer<String>();
  getHttpData(
onComplete: (results) {
completer.complete(results);
},
onError: (error) {
completer.completeError(error);
}
);
  return completer.future;
}

How about we skip the call getHttpData() for the second and check out at the last line of asyncQuery()? There, we return the future occurrence related to the completer we’ve started up. At the point when our capability is executed, the completer (and future) are made, then the network call happens asynchronously as we register the callbacks it needs.

The getHttpData() function takes two boundaries, the first being a completion callback and the second an error callback. The finish callback finishes the future we’ve previously returned, sending results with it. With this example, you can keep clients of your code from being required to manage callbacks, permitting them to get data by getHttpData() utilizing the less complex future worldview.

Wrapping a persistent connection to use futures

If your application collaborates with a tireless association, utilizing attachments or something almost identical, expecting a reaction from the socket server in the wake of making a request is normal. Over a stateful, relentless association, your application can’t foresee when or in what request reactions or other spontaneous messages might show up.

To show this example, we should take a gander at an extract from an socket service class you could use in your application:

class SocketService {
final _socketConnection = SomeSocketConnection();
final Map<String, Completer<String>> _requests = {};
  Future<String> sendSocketMessage(String data) {
final completer = Completer<String>();
final requestId = getUniqueId();
    final request = {
'id': requestId,
'data': data,
};
    _requests[requestId] = completer;
    _socketConnection.send(jsonEncode(request));
    return completer.future;
}
  void _onSocketMessage(String json) {
final decodedJson = jsonDecode(json);
final requestId = decodedJson['id'];
final data = decodedJson['data'];
    if (_requests.containsKey(requestId)) {
_requests[requestId].complete(data);
_requests.remove(requestId);
}
}
}

As referenced, this is only a passage, yet what’s incorporated will exhibit the future administration pattern. The class gets going by introducing an imaginary socket association object and a vacant map that is utilized to monitor dynamic attachment demands. The map will involve string demand IDs as keys and completers as values, making a table of completers.

To monitor which solicitations are related to which response, we want to create an exceptional ID and connect it to each ask. The socket server should incorporate that equivalent ID with every response. Along these lines, when socket messages show up, we can analyze the ID and find it in our solicitation table to decide whether the message is a reaction to a prior demand

The public sendSocketRequest() method accepts a few string information as a contention and returns a future. The strategy initially makes a couple of comfort factors as it produces a completer and a request ID for the request.

Note that there is no real getUniqueId() function. You can create unique IDs by anything implies you favor. Then, we put the ID and the data into a Map<String, dynamic> so we can encode it as JSON to be sent over the attachment.

final response = await mySocketService.sendSocketMessage("Hi!");

The response variable will be filled when a response to this particular request is gotten by the client application, and this calling code never needs to realize pretty much all the accounting occurring in the background to keep requests and responses accurately matched.

Conclusion

I hope this blog will provide you with sufficient information on Trying up the Explore Futures & Completers In Dart & Flutter in your projectsNow you know how to make interacting with callback libraries easier using Dart futures and completers.

❤ ❤ 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.


Action Chip In Flutter

0

Material Design has conservative components called chips. Action chip is one of the chips. Typically, it’s utilized to set off an action when the user presses the chip. Flutter makes it more straightforward for us to make an action chip by giving us a widget called ActionChip.

This blog will explore the Action Chip In Flutter. We perceive how to execute a demo program. We will learn how to use the Action Chip and how to customize your flutter applications.

ActionChip class – material library – Dart API
A Material Design action chip. Action chips are a set of options that trigger an action related to primary content…api. flutter.dev

Table Of Contents::

Introduction

Constructor

Properties

Code Implement

Code File

Conclusion



Introduction:

ActionChip is a material widget in a flutter. The actual name proposes that they are utilized to set off some action. Action chips ought to be made progressively founded on the context of the essential substance.

We can’t incapacitate an action chip so showing it to the user without its purpose is better not. Flutter gives a widget called ActionChip which permits us to add an action chip to our application.

Demo Module::

This demo video shows how to use the action chip in a flutter and shows how an action chip will work in your flutter applications. We will show a user press the chip then, the chip will trigger an action. It will be shown on your devices.

Constructor:

To utilize ActionChip, you need to call the constructor underneath:

To make an action chip in flutter we need to call the constructor of the ActionChip class given by flutter. ActionChip has two required properties label and onPressed callback.

const ActionChip({
Key? key,
this.avatar,
required this.label,
this.labelStyle,
this.labelPadding,
required this.onPressed,
this.pressElevation,
this.tooltip,
this.side,
this.shape,
this.clipBehavior = Clip.none,
this.focusNode,
this.autofocus = false,
this.backgroundColor,
this.padding,
this.visualDensity,
this.materialTapTargetSize,
this.elevation,
this.shadowColor,
})

Without utilizing these properties we can’t make an action chip. We need to set the label with a widget, typically a text widget. The onPressed callback is utilized to play out any action when the chip is squeezed.

Properties:

There are some properties of ActionChip are:

  • > avatar — This property is used to add an avatar to the action chip.
  • > shape — This property is used to change the shape of the action chip.
  • > shadowColor — This property is used to apply color to the shadow which appears when the chip has elevation.
  • > pressElevation — This property is used to provide elevation when the chip is pressed.
  • > onPressed — This property is used to perform some action when we press the chip.
  • > labelStyle — This property is used to apply a style to the label like changing font size, font family, text color, etc.
  • > backgroundColor — This property is used to change the background color of the action chip.
  • > side — This property is used to apply a border to the action chip.

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 the main. dart file, we will create a new class MyHomePage(). In this class, we will create a bool selected that is equal to the false.

bool selected = false;

In the body, we will add a Center widget. In this widget, we will add a Column widget and add an image with height and width. Also, we will add a Container widget.

Center(
child: Column(
children: [
Image.asset(
"assets/logo.png",
height: 300,
width: 350,
),
Container(
alignment: Alignment.topCenter,
margin: const EdgeInsets.only(top: 20),
child: ActionChip(
backgroundColor: Colors.brown.shade200,
padding: const EdgeInsets.only(top: 20,left: 20, right: 20,bottom: 20),
avatar: selected ? const CircularProgressIndicator() : null,
label: Text(selected ? "Cancel" : "Download",style: const TextStyle(fontSize: 16),),
onPressed: () {
selected = !selected;
setState(() {});
},
elevation: 8),
),
],
),
)

On this widget, we will add an alignment was the topCenter and add an ActionChip widget. Inside the widget, we will add backgroundColor, padding, avatar, label, elevation, and onPressed function. In this function, we will add selected equal not selected.

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

Output

Code File:

import 'package:flutter/material.dart';
import 'package:flutter_action_chip_demo/splash_screen.dart';

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

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

@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.brown,
),
home: const Splash(),
debugShowCheckedModeBanner: false,
);
}
}

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

@override
_MyHomePageState createState() {
return _MyHomePageState();
}
}

class _MyHomePageState extends State<MyHomePage> {
bool selected = false;

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text(
"Flutter Action Chip Demo",
style: TextStyle(color: Colors.black),
),
centerTitle: true,
automaticallyImplyLeading: false,
backgroundColor: Colors.brown.shade200,
),
body: Center(
child: Column(
children: [
Image.asset(
"assets/logo.png",
height: 300,
width: 350,
),
Container(
alignment: Alignment.topCenter,
margin: const EdgeInsets.only(top: 20),
child: ActionChip(
backgroundColor: Colors.brown.shade200,
padding: const EdgeInsets.only(
top: 20, left: 20, right: 20, bottom: 20),
avatar: selected ? const CircularProgressIndicator() : null,
label: Text(
selected ? "Cancel" : "Download",
style: const TextStyle(fontSize: 16),
),
onPressed: () {
selected = !selected;
setState(() {});
},
elevation: 8),
),
],
),
));
}
}

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying the Action Chip in your flutter projectsWe will show you what the Introduction is and what are the construction and properties of the Action Chip, and make a demo program for working with Action Chip 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! For any flutter-related queries, you can connect with us on FacebookGitHubTwitter, 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.


Filter Chip In Flutter

0

An assortment of filter chips is typically utilized where the user can choose different choices. Making a filter chip in Flutter should be possible by utilizing the FilterChip widget which is exceptionally simple to utilize.

This blog will explore the Filter Chip In Flutter. We perceive how to execute a demo program. We will learn how to use the Filter Chip and how to customize your flutter applications.

FilterChip class – material library – Dart API
A Material Design filter chip. Filter chips use tags or descriptive words as a way to filter content. Filter chips are…api. flutter.dev

Table Of Contents::

Introduction

Constructor

Properties

Code Implement

Code File

Conclusion



Introduction:

FilterChip is a material design widget in a flutter. Filter chips are utilized when we believe that the client should choose different choices from a gathering of chips.

Flutter gives a widget called FilterChip which permits us to add a filter chip to our application. They can be utilized in the spot of Checkbox or Switch widgets. It requires one of its precursors to be a Material widget.

Demo Module ::

This demo video shows how to use the filter chip in a flutter and shows how a filter chip will work in your flutter applications. We will show a user choose the many choices from a group of chips. It will be shown on your devices.

Construction:

To utilize FilterChip, you need to call the constructor underneath:

To create a filter chip in flutter we have to call the constructor of the FilterChip class provided by flutter. There are two required properties for the FilterChip widget which are label and onSelected callback.

To make a filter chip in flutter we need to call the constructor of the FilterChip class given by flutter. There are two required properties for the FilterChip widget which are label and onSelected callback.

const FilterChip({
Key? key,
this.avatar,
required this.label,
this.labelStyle,
this.labelPadding,
this.selected = false,
required this.onSelected,
this.pressElevation,
this.disabledColor,
this.selectedColor,
this.tooltip,
this.side,
this.shape,
this.clipBehavior = Clip.none,
this.focusNode,
this.autofocus = false,
this.backgroundColor,
this.padding,
this.visualDensity,
this.materialTapTargetSize,
this.elevation,
this.shadowColor,
this.selectedShadowColor,
this.showCheckmark,
this.checkmarkColor,
this.avatarBorder = const CircleBorder(),
})

Without utilizing these properties we can’t make a filter chip. We need to set the name with a widget, normally a text widget. The onSelected callback is utilized to address whether the chip is chosen or unselected.

Properties:

There are some properties of FilterChip are:

  • > selected — This property is utilized to show whether the chip is chosen or unselected. It takes a boolean value setting true will make the chip chosen and false will make the chip unselected.
  • > onSelected — This property is utilized to update the chosen or unselected condition of the decision chip and to play out certain activities when the chip is chosen or unselected.
  • > showCheckmark — This property is used to show/hide the checkmark that appears when the chip is selected. It is a boolean value. Setting true will make the checkmark visible and false will make it invisible. By default the value is true.
  • > pressElevation — This property is used to change the amount of elevation we want to apply when we press the chip.
  • > backgroundColor — This property is used to add/change the background color of the filter chip.
  • > elevation — This property is used to apply elevation to the filter chip.

How to implement code in dart file :

You need to implement it in your code respectively:

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

First, we want an ItemModel class for holding the information of Filterchip. The List will hold the objects of type ItemModel which is a pojo class. The pojo class will have three parameters label, color, and isSelected.

import 'dart:ui';

class ItemModel {
String label;
Color color;
bool isSelected;

ItemModel(this.label, this.color, this.isSelected);
}

The label will hold the label of the chip, the color will hold the backgroundColor and isSelected will hold the chosen or unselected condition of the filter chip.

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

In the main. dart file, we will create a new class MyHomePage(). In this class, we will first create a List of types ItemModel and provide the data for chips.

final List<ItemModel> _chipsList = [
ItemModel("Android", Colors.green, false),
ItemModel("Flutter", Colors.blueGrey, false),
ItemModel("Ios", Colors.deepOrange, false),
ItemModel("Python", Colors.cyan, false),
ItemModel("React JS", Colors.teal, false),
];

We will create a bool selected is equal to the false

bool selected = false;

In the body, we will be a Column widget. In this widget, we will add an image with height and width. We will add a Wrap widget. in this widget, we will add a spacing was 8, the direction was the horizontal axis, and the filterChipsList() method. We will below define the method with the code.

Column(
children: [
Image.asset(
"assets/logo.png",
height: 300,
width: 350,
),
Wrap(
spacing: 8,
direction: Axis.horizontal,
children: filterChipsList(),
),
],
),

Now we will deeply define filterChipsList() method are:

This method was on the list of widgets. We will add the FilterChip widget. In this widget, we will add a label, backgroundColor, selected, labelStyle selected, onSelected, and then return chips.

List<Widget> filterChipsList() {
List<Widget> chips = [];
for (int i = 0; i < _chipsList.length; i++) {
Widget item = Padding(
padding: const EdgeInsets.only(left: 10, right: 5),
child: FilterChip(
label: Text(_chipsList[i].label),
labelStyle: const TextStyle(color: Colors.white,fontSize: 16),
backgroundColor: _chipsList[i].color,
selected: _chipsList[i].isSelected,
onSelected: (bool value) {
setState(() {
_chipsList[i].isSelected = value;
});
},
),
);
chips.add(item);
}
return chips;
}

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';
import 'package:flutter_filter_chips_demo/item_model.dart';
import 'package:flutter_filter_chips_demo/splash_screen.dart';

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

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

@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.blueGrey,
),
debugShowCheckedModeBanner: false,
home: const Splash(),
);
}
}

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

@override
_MyHomePageState createState() {
return _MyHomePageState();
}
}

class _MyHomePageState extends State<MyHomePage> {
bool selected = false;
final List<ItemModel> _chipsList = [
ItemModel("Android", Colors.green, false),
ItemModel("Flutter", Colors.blueGrey, false),
ItemModel("Ios", Colors.deepOrange, false),
ItemModel("Python", Colors.cyan, false),
ItemModel("React JS", Colors.teal, false),
];

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Flutter Filter Chip Demo"),
automaticallyImplyLeading: false,
centerTitle: true,
),
body: Center(
child: Column(
children: [
Image.asset(
"assets/logo.png",
height: 300,
width: 350,
),
Wrap(
spacing: 8,
direction: Axis.horizontal,
children: filterChipsList(),
),
],
),
));
}

List<Widget> filterChipsList() {
List<Widget> chips = [];
for (int i = 0; i < _chipsList.length; i++) {
Widget item = Padding(
padding: const EdgeInsets.only(left: 10, right: 5),
child: FilterChip(
label: Text(_chipsList[i].label),
labelStyle: const TextStyle(color: Colors.white,fontSize: 16),
backgroundColor: _chipsList[i].color,
selected: _chipsList[i].isSelected,
onSelected: (bool value) {
setState(() {
_chipsList[i].isSelected = value;
});
},
),
);
chips.add(item);
}
return chips;
}
}

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying the Filter Chip in your flutter projectsWe will show you what the Introduction is and what are the construction and properties of the Filter Chip, and make a demo program for working with Filter Chip 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! For any flutter-related queries, you can connect with us on FacebookGitHubTwitter, 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.


Cupertino Timer Picker In Flutter

0

The most excellent portable applications up to this point we have seen had clicks and contacts and motions taps and adding these connections in a mobile application was so difficult, However, Flutter acts to the rescue and assists you with building the most Lovely application encounters across various stages with the equivalent codebase.
We can establish the point in time for a countdown timer utilizing a timer picker. Rather than using it as a picker for a countdown timer, we can on the other hand involve it as a time picker.

This article will explore the Cupertino Timer Picker In Flutter. We will see how to implement a demo program. Learn how to create an ios style CupertinoTimerPicker and also learn how to customize the style of the CupertinoTimerPicker widget using different properties.in your flutter applications.

Table Of Contents::

Introduction

Constructor

Parameters

Code Implement

Code File

Conclusion



Introduction:

Cupertino timer picker in flutter is an ios style countdown timer picker. Utilizing the CupertinoTimerPicker widget we can add an ios style countdown timer picker to our application. A timer picker allows us to establish the point in time for a countdown timer. We can likewise involve it as a time picker for picking time as opposed to involving it as a selector for a countdown timer.

By and large, we will utilize a countdown timer to show the time left in a web-based assessment or before sending off an occasion, and so on. It will show the countdown duration in hours, minutes, and seconds. The greatest span we can set is 23 hours 59 minutes and 59 seconds.

Demo Module ::

This demo video shows how to create a Cupertino timer picker in a flutter and shows how a Cupertino timer picker will work in your flutter applications. We will show a button, when a user press a button, then show a model popup for the chosen timer. It will be shown on your device.

Constructor:

To utilize CupertinoTimerPicker, you need to call the constructor underneath:

To make a Cupertino timer picker in flutter we need to utilize CupertinoTimerPicker class. Calling the constructor and giving the necessary properties will accomplish the work. It has one required property onTimerDurationChanged. It takes a callback capability as a value.

CupertinoTimerPicker({
Key? key,
this.mode = CupertinoTimerPickerMode.hms,
this.initialTimerDuration = Duration.zero,
this.minuteInterval = 1,
this.secondInterval = 1,
this.alignment = Alignment.center,
this.backgroundColor,
required this.onTimerDurationChanged,
})

We don’t need to show a timer picker consistently like different widgets. We need to show it when an occasion triggers. For instance, on the snap of a button, or some other widget. For the most part, we will show a timer picker utilizing showCupertinoModalPopup or showModalBottomSheet.

Properties:

There are some properties of CupertinoTimerPicker are:

  • > mode — This Property is utilized to change the mode of the timer picker. It accepts the CupertinotimerPickerMode consistent as a value. It has three constants hm, ms, and hms. Naturally, it is hms (hours minutes seconds).
  • > initialTimeDuration — This Property is used to the InitialTimerDuration has a default value of 0 and a maximum value of 23 hours 59 minutes 59 seconds.
  • > minuteInterval — This Property is used to change the interval between the minutes of the timer picker we will use this property. It takes double as value. By default, it is 1.
  • > secondInterval — This Property is used to change the seconds of the timer picker we will use this property. It also takes double as a value which is 1 by default.
  • > alignment — This Property is used for the Classes generated with Alignment and its variations are acceptable in a property or argument of this kind.
  • > backgroundColor — This Property is utilized in this parameter to alter the picker’s background color. CupertinoColors or the colors class steady are acknowledged as values.
  • > onTimerDurationChanged — This Property is used for the callback function is the value it accepts. Every time the user modifies the time in the picker, this function is called. The most recent time will be obtained through this method. We will use the setState() function to update the UI with this value.

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 the main. dart file, we will create a MyHomePage class. We will create a Duration initialTimer is equal to the Duration() and also create var time.

Duration initialTimer = const Duration();
var time;

Now, we will create a widget was timerPicker(). In this widget, we will return the CupertinoTimerPicker method. In this method, we will add a mode was CupertinoTimerPickerMode.hms, minuteInterval was 1, secondInterval was also 1, and initialTimerDuration was initialTimer.

Widget timerPicker() {
return CupertinoTimerPicker(
mode: CupertinoTimerPickerMode.hms,
minuteInterval: 1,
secondInterval: 1,
initialTimerDuration: initialTimer,
onTimerDurationChanged: (Duration changeTimer) {
setState(() {
initialTimer = changeTimer;
time =
'${changeTimer.inHours} hrs ${changeTimer.inMinutes % 60} mins ${changeTimer.inSeconds % 60} secs';
});
},
);
}

Also, we will add the onTimerDurationChanged property. In this property, we will add inside a setState() function. In this function, we will add initialTimer is equal to the changeTimer and time is equal to the hrs, mins, and sec.

Now, we will create a widget was _buildContainer(Widget picker).

In this widget, we will return a Container with height, padding, and color, and the child was DefaultTextStyle() method. In this method, we will add GestureDetector().

Widget _buildContainer(Widget picker) {
return Container(
height: 200,
padding: const EdgeInsets.only(top: 6.0),
color: CupertinoColors.white,
child: DefaultTextStyle(
style: const TextStyle(
color: CupertinoColors.black,
fontSize: 22.0,
),
child: GestureDetector(
onTap: () {},
child: SafeArea(
top: false,
child: picker,
),
),
),
);
}

Now, in the body, we will add the Inkwell widget. In this widget, we will add the onTap() function. In this function, we will add showCupertinoModalPopup. Also, we will add a Container with height and add the text “Cupertino Timer Picker”. Also, adding other text was times ie equal to null then show ‘No Select Time’ else show ‘time’ when the user was selected

InkWell(
onTap: () {
showCupertinoModalPopup<void>(
context: context,
builder: (BuildContext context) {
return _buildContainer(timerPicker());
});
},
child: Column(
children: [
Container(
height: 50,
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
color: Colors.cyan),
child: const Center(
child: Text(
"Cupertino Timer Picker",
style: TextStyle(color: Colors.white, fontSize: 17),
),
),
),
Container(
padding: const EdgeInsets.only(top: 8, bottom: 8),
child: Text(
time == null ? 'No Select Time' : ' $time',
style: const TextStyle(
color: Colors.black,
fontSize: 16,
fontWeight: FontWeight.bold),
),
),
],
),
),

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/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_cupertino_timerpicker_demo/splash_screen.dart';

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

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

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

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

@override
_MyHomePageState createState() {
return _MyHomePageState();
}
}

class _MyHomePageState extends State {
Duration initialTimer = const Duration();
var time;

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Flutter Cupertino Timer Picker Demo"),
automaticallyImplyLeading: false,
centerTitle: true,
backgroundColor: Colors.green,
),
body: Padding(
padding: const EdgeInsets.all(16.0),
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
Image.asset(
"assets/logo.png",
height: 200,
),
const SizedBox(
height: 50,
),
InkWell(
onTap: () {
showCupertinoModalPopup<void>(
context: context,
builder: (BuildContext context) {
return _buildContainer(timerPicker());
});
},
child: Column(
children: [
Container(
height: 50,
width: MediaQuery.of(context).size.width,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(8),
color: Colors.cyan),
child: const Center(
child: Text(
"Cupertino Timer Picker",
style: TextStyle(color: Colors.white, fontSize: 17),
),
),
),
Container(
padding: const EdgeInsets.only(top: 8, bottom: 8),
child: Text(
time == null ? 'No Select Time' : ' $time',
style: const TextStyle(
color: Colors.black,
fontSize: 16,
fontWeight: FontWeight.bold),
),
),
],
),
),
],
),
),
);
}

Widget timerPicker() {
return CupertinoTimerPicker(
mode: CupertinoTimerPickerMode.hms,
minuteInterval: 1,
secondInterval: 1,
initialTimerDuration: initialTimer,
onTimerDurationChanged: (Duration changeTimer) {
setState(() {
initialTimer = changeTimer;
time =
'${changeTimer.inHours} hrs ${changeTimer.inMinutes % 60} mins ${changeTimer.inSeconds % 60} secs';
});
},
);
}

Widget _buildContainer(Widget picker) {
return Container(
height: 200,
padding: const EdgeInsets.only(top: 6.0),
color: CupertinoColors.white,
child: DefaultTextStyle(
style: const TextStyle(
color: CupertinoColors.black,
fontSize: 22.0,
),
child: GestureDetector(
onTap: () {},
child: SafeArea(
top: false,
child: picker,
),
),
),
);
}
}

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying the Cupertino Timer Picker in your flutter projectsWe will show you what the Introduction is and what are the construction and properties of the Choice Chip, and make a demo program for working with Cupertino Timer Picker 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! For any flutter-related queries, you can connect with us on FacebookGitHubTwitter, 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.


Implement Listener Class in Flutter

0

When you will code for building anything in Flutter, it will be inside a widget. The focal intention is to make the application out of widgets. It depicts how your application view ought to look with its ongoing design and state. At the point when you make any modification in the code, the widget rebuilds its depiction by working out the distinction between the past and current widgets to decide the negligible changes for delivering in the UI of the application.

Widgets are settled with one another to fabricate the application. It implies the root of your application is itself a widget, and right down is a widget too. For instance, a widget can show something, characterize configuration, handle cooperation, and so on.

This blog will explore the Implement Listener Class in Flutter. We perceive how to execute a demo program. We will learn how to use the Listener class in your flutter applications.

Listener class – widgets library – Dart API
A widget that calls callbacks in response to common pointer events. It listens to events that can construct gestures…api. flutter.dev

Table Of Contents::

Introduction

Constructor

Properties

Code Implement

Code File

Conclusion



Introduction:

A widget called the Listener triggers callbacks in light of continuous pointer events. It focuses on things like when the cursor is squeezed, moved, delivered, or dropped which can make motions. It doesn’t focus on mouse-explicit occasions as when the mouse shows up, leaves, or floats over an area without clicking any buttons.

Use MouseRegion Class for these occasions. While contrasting the list of items that a mouse pointer is floating on between this edge and the past casing, MouseRegion is utilized. This incorporates moving mouse cursors, beginning occasions, and finishing occasions. Use Listener or, ideally, GestureDetector Class to pay attention to normal pointer events.

Demo Module::

This demo video shows how to use the listener class in a flutter and shows how a listener class will work in your flutter applications. We will show a user press or release screen many times, then the value will be shown on your devices.

Constructor:

To utilize Listener, you need to call the constructor underneath:

const Listener({
Key? key,
this.onPointerDown,
this.onPointerMove,
this.onPointerUp,
this.onPointerHover,
this.onPointerCancel,
this.onPointerSignal,
this.behavior = HitTestBehavior.deferToChild,
Widget? child,
})

Properties:

There are some properties of Listener are:

  • onPointerDown: This property is utilized to Callers can be informed regarding these events in a widget tree thanks to the listener.onPointerDown capability.
  • onPointerMove: This property is utilized while the pointer is in contact with the object, it has moved about that object.
  • onPointerUp: This property is utilized to the pointer is no longer near the object.
  • onPointerHover: This property is utilized while the pointer is not in contact with the device, it has moved about it.
  • onPointerCancel: This property is utilized to the input from the pointer is no longer directed towards this receiver.
  • onPointerSignal: This property is utilized to Pointer signals are discrete events that come from the pointer but don’t affect the state of the pointer itself. They don’t have to be understood in the context of a chain of events to be understood.
  • HitTestBehavior behavior: This property is utilized only if one of their children is struck by the hit test do targets that defer to their children get events within their boundaries?
  • child: This property is used in the Flutter framework’s primary class ordered progression is built of widgets. An immutable depiction of a part of a UI is alluded to as a widget. Components that administer the basic render tree can be made by blowing up widgets.

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 the main. dart file, we will create a new class was ListenerDemo. In this class, we will create two integer variables that were _down and _up is equal to zero. Also, creating another two double variables x and y is equal to zero.

int _down = 0;
int _up = 0;
double x = 0.0;
double y = 0.0;

Now, we will create a _updateLocation() method. In this method, we will add setState() function. In this function, we will add x as equal to the details.position.dx and y are equal to the details.position.dy.

void _updateLocation(PointerEvent details) {
setState(() {
x = details.position.dx;
y = details.position.dy;
});
}

Then, we will create _incrementDown() and _incrementUp() methods. In _incrementDown, we will add the _updateLocation(details) and add setState() function. In this function, add _down++. In _incrementUp, we will add the _updateLocation(details) and add setState() function. In this function, add _up++.

void _incrementDown(PointerEvent details) {
_updateLocation(details);
setState(() {
_down++;
});
}

void _incrementUp(PointerEvent details) {
_updateLocation(details);
setState(() {
_up++;
});
}

In the body, we will add the ConstrainedBox widget. In this widget, we will add Listener() widget. In this widget, we will add onPointerDown is equal to the _incrementDown method, onPointerMove is equal to the _updateLocation method, and onPointerUp is equal to the _incrementUp method.

ConstrainedBox(
constraints: BoxConstraints.tight(const Size(380.0, 300.0)),
child: Listener(
onPointerDown: _incrementDown,
onPointerMove: _updateLocation,
onPointerUp: _incrementUp,
child: Container(
color: Colors.orange[200],
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'You have pressed or released this area this many times:'),
const SizedBox(height: 15,),
Text(
'$_down presses\n$_up releases',
style: Theme.of(context).textTheme.headline3,
),
const SizedBox(height: 15,),
Text(
'The cursor is here: (${x.toStringAsFixed(2)}, ${y.toStringAsFixed(2)})',
),
],
),
),
),
),

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';
import 'package:flutter_listener_demo/splash_screen.dart';

void main() => runApp(const MyApp());

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

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

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

@override
State createState() => _ListenerDemoState();
}

class _ListenerDemoState extends State {
int _down = 0;
int _up = 0;
double x = 0.0;
double y = 0.0;

void _incrementDown(PointerEvent details) {
_updateLocation(details);
setState(() {
_down++;
});
}

void _incrementUp(PointerEvent details) {
_updateLocation(details);
setState(() {
_up++;
});
}

void _updateLocation(PointerEvent details) {
setState(() {
x = details.position.dx;
y = details.position.dy;
});
}

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Flutter Listener Class Demo"),
centerTitle: true,
automaticallyImplyLeading: false,
backgroundColor: Colors.orangeAccent[400],
),
body: Center(
child: ConstrainedBox(
constraints: BoxConstraints.tight(const Size(380.0, 300.0)),
child: Listener(
onPointerDown: _incrementDown,
onPointerMove: _updateLocation,
onPointerUp: _incrementUp,
child: Container(
color: Colors.orange[200],
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: [
const Text(
'You have pressed or released this area this many times:'),
const SizedBox(
height: 15,
),
Text(
'$_down presses\n$_up releases',
style: Theme.of(context).textTheme.headline3,
),
const SizedBox(
height: 15,
),
Text(
'The cursor is here: (${x.toStringAsFixed(2)}, ${y.toStringAsFixed(2)})',
),
],
),
),
),
),
),
);
}
}

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying the Listener in your flutter projectsWe will show you what the Introduction is and what are the construction and properties of the Listener, and make a demo program for working with Listener 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.


Choice Chip In Flutter

0

A choice chip is a sort of Material Plan chip. Choice chips permit the choice of a solitary chip from a set of choices. In Flutter, there is a committed widget called ChoiceChip that permits you to effectively make activity chips.

This blog will explore the Choice Chip In Flutter. We perceive how to execute a demo program. We will learn how to use the Choice Chip in your flutter applications.

ChoiceChip class – material library – Dart API
A Material Design choice chip. ChoiceChip s represent a single choice from a set. Choice chips contain related…api. flutter.dev

Table Of Contents ::

Introduction

Constructor

Properties

Code Implement

Code File

Conclusion



Introduction:

A choice chip is a material widget in a flutter. The choice chip permits the client to make a solitary choice from a set/gathering of chips. It contains a comparable sort of text or classification.

Flutter gives a widget considered ChoiceChip that allows us to add the choice chip to our application. It requires one of its precursors to be a Material widget.

Demo Module ::

This demo video shows how to use the choice chip in a flutter and shows how a choice chip will work in your flutter applications. We will show a user press the chip, then the chip will be selected. It will be shown on your devices.

Constructor:

To utilize ChoiceChip, you need to call the constructor underneath:

To create a choice chip in flutter we have to use the constructor of the ChoieChip class provided by flutter.

To make a choice chip in flutter we need to utilize the constructor of the ChoieChip class given by flutter.

const ChoiceChip({
Key? key,
this.avatar,
required this.label,
this.labelStyle,
this.labelPadding,
this.onSelected,
this.pressElevation,
required this.selected,
this.selectedColor,
this.disabledColor,
this.tooltip,
this.side,
this.shape,
this.clipBehavior = Clip.none,
this.focusNode,
this.autofocus = false,
this.backgroundColor,
this.padding,
this.visualDensity,
this.materialTapTargetSize,
this.elevation,
this.shadowColor,
this.selectedShadowColor,
this.avatarBorder = const CircleBorder(),
})

There are two required properties for the ChoiceChip widget which are labeled and selected. The label can be any widget normally a text widget and selected is a boolean value that is utilized to demonstrate whether the label is chosen or unselected. To utilize a choice chip we need to furnish these properties for certain qualities.

Properties:

There are some properties of ChoiceChip are:

  • > selected — This property is utilized to set the chip’s state to be chosen or unselected. It takes a boolean value setting true will make the chip chosen and false will make the chip unselected.
  • > onSelected — This property is utilized to update the chosen or unselected condition of the choice chip and to play out certain activities when the chip is chosen or unselected.
  • > selectedColor This property is used to apply color to the chip when the chip is selected.
  • > pressElevation — This property is used to change the amount of elevation we want to apply when we press the chip.
  • > selectedShadowColor — This property is used to apply shadow color to the chip when the chip is transforming from a selected state to unselected state.
  • > backgroundColor — This property is used to add/change the background color of the choice chip.
  • > shadowColor — This property is used to apply color to the shadow that appears when the chip is elevated.

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 the first place, we want a pojo class for holding the information of the choice chip. The pojo class will have two parameters label and color. The label will hold the text to be shown as the label of the chip and the variety will hold the backgroundColor of the chip.

class Data {
String label;
Color color;

Data(this.label, this.color);
}

Now let’s create a List of type Data (pojo) and provide the data for chips.

final List<Data> _choiceChipsList = [
Data("Android", Colors.green),
Data("Flutter", Colors.blue),
Data("Ios", Colors.deepOrange),
Data("Python", Colors.cyan),
Data("React", Colors.pink)
];

We will also create an integer variable was _selectedIndex.

int? _selectedIndex;

In the body, we will add the Column widget. In this widget, we will add an image and wrap widget. In this widget, we will add direction was horizontal, the spacing was six, and its children were choiceChips() method. We will define deeply describe it below with the code.

Center(
child: Column(
children: [
Image.asset(
"assets/logo.png",
height: 300,
width: 350,
),
Wrap(
spacing: 6,
direction: Axis.horizontal,
children: choiceChips(),
),
],
),
)

Now we will deeply define choiceChips() method are:

This method was on the list of widgets. We will add the ChoiceChip widget. In this widget, we will add a label, backgroundColor, selected, labelStyle selectedColor, onSelected, and then return chips.

List<Widget> choiceChips() {
List<Widget> chips = [];
for (int i = 0; i < _choiceChipsList.length; i++) {
Widget item = Padding(
padding: const EdgeInsets.only(left: 10, right: 5),
child: ChoiceChip(
label: Text(_choiceChipsList[i].label),
labelStyle: const TextStyle(color: Colors.white),
backgroundColor: _choiceChipsList[i].color,
selected: _selectedIndex == i,
selectedColor: Colors.black,
onSelected: (bool value) {
setState(() {
_selectedIndex = i;
});
},
),
);
chips.add(item);
}
return chips;
}

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';
import 'package:flutter_choice_chip_demo/splash_screen.dart';

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

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

@override
Widget build(BuildContext context) {
return MaterialApp(
theme: ThemeData(
primarySwatch: Colors.green,
),
debugShowCheckedModeBanner: false,
home: const Splash(),
);
}
}

class Data {
String label;
Color color;

Data(this.label, this.color);
}

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

@override
_MyHomePageState createState() {
return _MyHomePageState();
}
}

class _MyHomePageState extends State<MyHomePage> {
int? _selectedIndex;
final List<Data> _choiceChipsList = [
Data("Android", Colors.green),
Data("Flutter", Colors.blue),
Data("Ios", Colors.deepOrange),
Data("Python", Colors.cyan),
Data("React", Colors.pink)
];

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: const Text("Flutter Choice Chip Demo"),
automaticallyImplyLeading: false,
centerTitle: true,
backgroundColor: Colors.blueGrey,
),
body: Center(
child: Column(
children: [
Image.asset(
"assets/logo.png",
height: 300,
width: 350,
),
Wrap(
spacing: 6,
direction: Axis.horizontal,
children: choiceChips(),
),
],
),
));
}

List<Widget> choiceChips() {
List<Widget> chips = [];
for (int i = 0; i < _choiceChipsList.length; i++) {
Widget item = Padding(
padding: const EdgeInsets.only(left: 10, right: 5),
child: ChoiceChip(
label: Text(_choiceChipsList[i].label),
labelStyle: const TextStyle(color: Colors.white),
backgroundColor: _choiceChipsList[i].color,
selected: _selectedIndex == i,
selectedColor: Colors.black,
onSelected: (bool value) {
setState(() {
_selectedIndex = i;
});
},
),
);
chips.add(item);
}
return chips;
}
}

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying the Choice Chip in your flutter projectsWe will show you what the Introduction is and what are the construction and properties of the Choice Chip, and make a demo program for working with Choice Chip 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! For any flutter-related queries, you can connect with us on FacebookGitHubTwitter, 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.