Google search engine
Home Blog Page 22

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.

Related: Explore Advanced Dart Enum

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


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.

Related: Filter Chip In Flutter

Related: Input Chip In Flutter

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


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.

Related: Action Chip In Flutter

Related: Input Chip In Flutter

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


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.

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


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.

Related: Wrap Class In Flutter

Related: Dart Generators & Callable Class In Flutter

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


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.

Related: Action Chip In Flutter

Related: Filter Chip In Flutter

Related: Input Chip In Flutter

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


Difference Between Ephemeral State & App State In Flutter

0

Numerous application advancements are sent off on the lookout, reliably working on the various applications’ worth. Flutter is one such innovation that is utilized in most present-day applications.

Out of the itemized course of Flutter improvement, dealing with the various states is a significant undertaking and incorporates two essential states-ephemeral states and an app state.

This blog will explore the Difference Between Ephemeral State & App State In Flutter. We will perceive how to execute a demo program and understand all about these states in detail in your flutter applications.

Table Of Contents::

What is State?

What is the Ephemeral State?

What is App State?

Difference between Ephemeral state and App state

Conclusion



What is State?

The state of an application incorporates fonts, textures, animation state, UI variables in the Flutter, the application’s resources, and so forth. Subsequently, all parts of the application’s memory comprise its state. The condition of an application is considered during the application’s plan, and large numbers of these parts, similar to textures, are overseen inside.

To change your widget, you want to update the state object, which should be possible by utilizing the setState() capability accessible for Stateful widgets. The setState() capability permits us to set the properties of the state object that sets off a redraw of the UI.

State the executives is one of the most famous and fundamental cycles in the lifecycle of an application. As indicated by official documentation, Flutter is decisive. It implies Flutter constructs its UI by mirroring the present status of your application.

All Flutter applications contain widgets; consequently, their state management is held simply by widgets. The key classification of the Flutter widgets incorporates:

> Stateless widget:

This widget, once made, can’t get changed or altered and has no inside state. It should be introduced again for changes or alterations.

> Stateful widget:

This widget contains a state and is dynamic. Thus, it is not difficult to alter and adjust this widget without re-introduction.
Hence, the key expresses that can be overseen incorporate the ephemeral state and application state. Tell us about these states individually.

What is the Ephemeral State?

It is likewise called local state or UI state. It is the condition of the application containing a solitary widget. There is no requirement for various state management strategies as it is connected with the particular state.

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

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

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

// This widget is the root of your application.
@override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
primarySwatch: Colors.green
),
debugShowCheckedModeBanner: false,
home: const Splash(),
);
}
}

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

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

class _MyHomePageState extends State {
String stringName = "Flutter";

@override
Widget build(BuildContext context) {
return ElevatedButton(
child: Text(
stringName,
style: const TextStyle(fontSize: 22),
),
onPressed: () {
setState(() {
stringName = stringName == "Flutter" ? "Flutter Devs" : "Flutter";
});
});
}
}

In the above model, the stringName is an ephemeral state. Here, just the setState() capability inside the StatefulWidget’s class can get to the stringName. The build strategy calls a setState() capability, which does the change in the state variables. At the point when this strategy is executed, the widget object is supplanted with the enhanced one, which gives the altered variable worth.

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

What is App State?

It is additionally called the shared state or application state. It is the condition of the application, which incorporates everything except the ephemeral state. The application state is utilized internationally and can be shared across the various pieces of the application. It very well may be kept between various client meetings.

The application state management is achieved utilizing the provider package, which is the outsider library. The three unique ideas concerning the equivalent are:

> ChangeNotifier:

It offers change notifications to the listeners and is a basic class that is not difficult to upgrade, implement, and comprehend. It tends to be utilized for a predetermined number of listeners and is utilized to notice a model for any change for the listener. The main strategy used to illuminate the listeners is “notifyListener().”

The “ChangeNotifier” extends the “Counter,” which notifies the listeners by calling “notify listeners().” The “ChangeNotifier” involves this single strategy for execution. Various functions like “increment” and “decrement” are utilized to increase or decrease the values.

class Counter with ChangeNotifier {
int _counter;

Counter(this._counter);

getCounter() => _counter;

setCounter(int counter) => _counter = counter;

void increment() {
_counter++;
notifyListeners();
}

void decrement() {
_counter--;
notifyListeners();
}
}

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

Output

> ChangeNotifierProvider:

This widget offers an example of the ChangeNotifier to its supporters. It is presented from the provider package and has a builder, making the new case of the Counter model. ChangeNotifierProvider consequently calls the “dispose()” technique on the Counter model when the example isn’t needed. Further, it doesn’t remake Counter until the need emerges.

It is not difficult to utilize MultiProvider assuming that there is a need to give more than one class. It eliminates the need to settle the current providers into the child of increasingly an as it contains a committed list of various providers in the extent of the class.

> Consumer:

It calls the provider in the new widget and further delegates the widget’s build implementation to the builder. Hence, this widget is kept as deep as possible in the tree.

It calls the provider in the new widget and further delegates the widget’s construct execution to the builder. Consequently, this widget is kept as profound as conceivable in the tree.

Difference between Ephemeral state and App state

Priorities straight, there is no widespread rule to recognize ephemeral states and application states in Flutter. This is because the application might have begun with the ephemeral state but may before long be moved to the application state with the expanded number of highlights.

Further, the starter application with each “Flutter make” incorporates “State” and “setState” to oversee various conditions of the Flutter applications. The other situation is the “_index” variable in the application state assuming the chosen tab in the base route bar isn’t the ephemeral state.

The flutter application utilizes various widgets. The information utilized by the majority of the widgets and a portion of the widgets goes under the application state. Simultaneously, the information utilized by a solitary widget goes under an ephemeral state. As widgets can begin utilizing information whenever given the application’s necessities and elements, the application state, and ephemeral state can be changed during the development cycle.

Conclusion:

I hope this blog will provide you with sufficient information on Trying the Difference Between Ephemeral State & App State In Flutter. Consequently, it becomes essential to figure out the distinction between its two main states- the ephemeral state and the app state.

The ephemeral state is specific to the single widget and is managed by “State” and “setState().” Everything excluding the ephemeral state is the app state. Further, with no clear demarcation between these two states, the difference is based on the complexity and app preferences. 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.

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


Cupertino Segmented Control In Flutter

0

The CupertinoSegmentedControl widget in Flutter shows widgets from a map in a horizontal list and makes an iOS-style portioned control bar. At the point when one choice in the segmented control is chosen, different choices in the divided control cease to be chosen.

This blog will explore the Cupertino Segmented Control In Flutter. We will see how to implement a demo program. We are going to learn about how we can utilize CupertinoSegmentedControl and how to customize the style of Cupertino Segmented Control using various properties in your flutter applications.

CupertinoSegmentedControl class – Cupertino library – Dart API
An iOS-style segmented control. Displays the widgets provided in the Map of children in a horizontal list. Used to…api. flutter.dev

Table Of Contents ::

Introduction

Constructor

Properties

Code Implement

Code File

Conclusion



Introduction:

Cupertino segmented control is the only ios style segmented control in a flutter. CupertinoSegmentedControl widget allows us to make a segmented control in ios style. It shows an even horizontal list of choices. We can choose a choice by tapping on it.

These choices are created utilizing a map (key-value pairs <String, widget>). The keys ought to be comparable for every one of the children on the map. We will utilize the keys to recognize the choice by the user. The values can be any widget and needn’t bother to be comparative. At the point when we select one choice, we can’t choose different choices in the segmented control. It implies we can’t choose more than each choice in time.

Demo Module ::

This demo video shows how to use a Cupertino segmented control in a flutter and shows how a Cupertino context menu will work in your flutter applications. It shows when the code successfully runs, then the user was tapping the button highlighted and shows the content. It will be shown on your device

Constructor:

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

To make a Cupertino segmented control in flutter we need to utilize CupertinoSegmentedControl class. Call the constructor of the class and give the required properties.

CupertinoSegmentedControl({
Key? key,
required this.children,
required this.onValueChanged,
this.groupValue,
this.unselectedColor,
this.selectedColor,
this.borderColor,
this.pressedColor,
this.padding,
})

The constructor has two required properties children & onValueChanged. The children should be of type map.

Properties:

There are some properties of CupertinoSegmentedControl are:

  • > children — This property is used for identifying keys and corresponding widget values in the segmented control. The map must have more than one entry. This attribute must be an ordered [Map] such as a [LinkedHashMap].
  • > onValueChanged — This property is used to take a callback function as a value. It will invoke every time the user selects an option. We can get the selected value inside this function. Based on the value we will update the UI.
  • > groupValue — This property is used to this indicates the option that is selected currently. It should be one of the keys in the map or null. If null no option is selected. If it is key then it will select the option for that key.
  • > selectedColor — This property is utilized to fill the background of the chosen widget and as the text color of unselected widgets. Defaults to [CupertinoTheme]’s ‘primary color’ if null.
  • > unselectedColor — This property is utilized to fill the backgrounds of unselected widgets and as the text color of the selected widget. Defaults to [CupertinoTheme]’s `primaryContrastingColor` if null.
  • > borderColor — This property is utilized for the color used as the border around each widget. Defaults to [CupertinoTheme]’s `primary color` if null.
  • > pressedColor — This property is utilized to the color used to fill the background of the widget the user is temporarily interacting with through a long press or drag. Defaults to the selected color at 20% opacity if null.
  • > padding — This property is utilized by the CupertinoSegmentedControl and will be placed inside this padding. Defaults to EdgeInsets.symmetric(horizontal: 16.0).

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, first, we will declare an integer variable that will hold the selected key. the selected value is equal to zero.

int selectedValue = 0;

We will show segmented control with three choices. We will show the comparing picture when the choice is chosen. For this, we will require a map for children and a list for holding pictures.

Map<int, Widget> children = <int, Widget>{
0: const Text("Flutter"),
1: const Text("NodeJS"),
2: const Text("React Native"),
};

Now we will declare the List with the path to images. Please download three images for flutter, node js, and react native. Name them as Flutter, NodeJS, and React Native. Add the images to the assets folder.

List<String> images = [
"assets/img1.png",
"assets/img2.png",
"assets/img3.png"
];

In the body part, we will add the column widget. In this widget, we will add the Container widget. In this widget, we will add the CupertinoSegmentedControl widget. We will add children, onValueChanged, and add some properties.

Column(
children: [
Container(
width: double.infinity,
child: CupertinoSegmentedControl<int>(
children: children,
onValueChanged: (value) {
selectedValue = value;
setState(() {});
},
selectedColor: CupertinoColors.black,
unselectedColor: CupertinoColors.white,
borderColor: CupertinoColors.inactiveGray,
pressedColor: CupertinoColors.inactiveGray,
groupValue: selectedValue,
),
),
Container(
height: MediaQuery.of(context).size.height * 0.60,
width: double.infinity,
child: Image.asset(images[selectedValue], fit: BoxFit.contain),
)
],
),

Also, we will add one more container widget with height and width for the images.

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_segmented_control_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.blue,
),
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> {
int selectedValue = 0;
Map<int, Widget> children = <int, Widget>{
0: const Text("Flutter"),
1: const Text("NodeJS "),
2: const Text("React Native"),
};

List<String> images = [
"assets/img1.png",
"assets/img2.png",
"assets/img3.png"
];

@override
Widget build(BuildContext context) {
return Scaffold(
backgroundColor: const Color(0xffFFFFFF),
appBar: AppBar(
title: const Text(
"Flutter Cupertino Segmented Control Demo",
style: TextStyle(fontSize: 19),
),
centerTitle: true,
automaticallyImplyLeading: false,
backgroundColor: Colors.teal,
),
body: Material(
child: Container(
margin: const EdgeInsets.only(top: 80, left: 20, right: 20),
child: Column(
children: [
Container(
width: double.infinity,
child: CupertinoSegmentedControl<int>(
children: children,
onValueChanged: (value) {
selectedValue = value;
setState(() {});
},
selectedColor: CupertinoColors.black,
unselectedColor: CupertinoColors.white,
borderColor: CupertinoColors.inactiveGray,
pressedColor: CupertinoColors.inactiveGray,
groupValue: selectedValue,
),
),
Container(
height: MediaQuery.of(context).size.height * 0.60,
width: double.infinity,
child: Image.asset(images[selectedValue], fit: BoxFit.contain),
)
],
),
),
),
);
}
}

Conclusion:

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

I hope this blog will provide you with sufficient information on Trying Cupertino Segmented Control in your flutter projectsWe will show you what the Introduction is. Make a demo program for working with Cupertino Segmented Control and you’ve learned how to create & use Cupertino Segmented Control 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 Facebook, GitHub, Twitter, and LinkedIn.

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

Related: Cupertino Timer Picker In Flutter

Related: Cupertino Popup Surface In Flutter

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


Inbuild List Methods In Dart

0

In Dart programming, the List data type is like exhibits in other programming dialects. A list is utilized to address an assortment of items. It is an arranged gathering of objects. The core libraries in Dart are answerable for the presence of the List class, its creation, and manipulation.

This blog will explore the Inbuild List Methods In Dart. We will see a few of the most common ones you should know for your next app. We are going to learn how to use it in our next projects.



for():

Runs a function on every component in the list

void main() {
List<String> bikes = [
'Harley-Davidson',
'Royal Enfield Hunter',
'Yamaha R15 V4',
'Yezdi Roadster',
'KTM Duke 200 ',
'Bajaj Pulsar NS200',
];
for (var bike in bikes) {
print(bike);
}
}

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


map():

Produces another list in the wake of changing every component in a given list

void main() {
List<String> bikes = [
'Harley-Davidson',
'Royal Enfield Hunter',
'Yamaha R15 V4',
'Yezdi Roadster',
'KTM Duke 200 ',
'Bajaj Pulsar NS200',
];
List<String> myBikes = bikes.map((bike) => 'I want $bike').toList();

for (var bike in myBikes) {
print(bike);
}
}

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


contains():

Checks to affirm that the given component is in the list

void main() {
List<String> bikes = [
'Harley-Davidson',
'Royal Enfield Hunter',
'Yamaha R15 V4',
'Yezdi Roadster',
'KTM Duke 200 ',
'Bajaj Pulsar NS200',
];
String key = 'Harley-Davidson';
String bikekey = 'myBike';
print('bikes contains $key');
print(bikes.contains(key));
print('bikes contains $bikekey');
print(bikes.contains(bikekey));
}

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


sort():

Order the components in view of the gave ordering function

void main() {
List<String> bikes = [
'Harley-Davidson',
'Royal Enfield Hunter',
'Yamaha R15 V4',
'Yezdi Roadster',
'KTM Duke 200 ',
'Bajaj Pulsar NS200',
];
print('Before: $bikes');
bikes.sort((a, b) => a.compareTo(b));
print('After: $bikes');
}

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


reduce() & fold():

Compresses the components to a solitary value and utilizing the given function

void main() {
List<int> marks = [70, 50, 95];
int totalMarks = marks.reduce((curr, next) => curr + next);
print('totalMarks : $totalMarks');
int initialGraceMarks = 40;
int graceTotalMarks = marks.fold(initialGraceMarks, (curr, next) => curr + next);
print('graceTotalMarks : $graceTotalMarks');
}

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


every():

Affirms that each component fulfills the test

void main() {
List<Map> attendance = [
{
'name': 'Yash',
'totalAttendance': 75,
},
{
'name': 'Rakhi',
'totalAttendance': 68,
},
{
'name': 'Pragati',
'totalAttendance': 38,
},
];
int levelOne = 45;
bool passedOne = attendance.every((totalAttendance) => totalAttendance['totalAttendance'] > levelOne);
print('levelOne :$levelOne PASSED : $passedOne');
int levelTwo = 33;
bool passedTwo = attendance.every((totalAttendance) => totalAttendance['totalAttendance'] > levelTwo);
print('levelTwo :$levelTwo PASSED : $passedTwo');
}

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


where(), firstWhere() & singleWhere():

Returns a collection of components that fulfill a test. firstWhere() returns the first match in the list, while singleWhere() returns the first match given there is precisely one match.

void main() {
List<Map> attendance = [
{
'name': 'Yash',
'totalAttendance': 75,
},
{
'name': 'Rakhi',
'totalAttendance': 68,
},
{
'name': 'Pragati',
'totalAttendance': 38,
},
];
int levelOne = 45;
List<Map> levelOneResult = attendance.where(
(totalAttendance) => totalAttendance['totalAttendance'] > levelOne,
).toList();print('levelOne :$levelOne levelOneResult : $levelOneResult');Map result1 = attendance.firstWhere(
(totalAttendance) => totalAttendance['totalAttendance'] == 38,
);print('Result: $result1');Map result2 = attendance.singleWhere(
(totalAttendance) => totalAttendance['totalAttendance'] < 38,
orElse: () => null,
);print('Result: $result2');
}

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


List.from():

Makes another list from the given assortment

class StudentAttendance {
String name;
int totalAttendance;
StudentAttendance(this.name, this.totalAttendance);
factory StudentAttendance.fromMap(Map data) => StudentAttendance(
data['name'],
data['totalAttendance'],
);
@override
toString() {
return '$name : $totalAttendance';
}
}

void main() {
List<Map> attendance = [
{
'name': 'Yash',
'totalAttendance': 75,
},
{
'name': 'Rakhi',
'totalAttendance': 68,
},
{
'name': 'Pragati',
'totalAttendance': 38,
},
];
List<StudentAttendance> attendanceList = List.from(attendance.map((data) => StudentAttendance.fromMap(data)));
for (var data in attendanceList) {
print(data.toString());
}
}

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


Conclusion:

In the article, I have explained the Inbuild List Methods In Dart basic structure in a flutter; you can modify this code according to your choice. This was a small introduction to Input 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 Inbuild List Methods in your projectsWe will show you the most common Inbuild List Methods in your applications. So please try it.

❤ ❤ Thanks for reading this article ❤❤

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

Clap 👏 If this article helps you.


From Our Parent Company Aeologic

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

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

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

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

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

Related: Sum Of a List Of Numbers In Dart

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


Input Chip In Flutter

0

There are a few chips characterized by Material Design, one of which is the input chip. Input chips are commonly used to address client input in a conservative structure or give ideas to the client. Besides label and avtar, an input chip can likewise have a delete icon. In Flutter, you can make that sort of chip utilizing the InputChip widget.

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

InputChip class – material library – Dart API
A material design input chip. Input chips represent a complex piece of information, such as an entity (person, place…api. flutter.dev

Table Of Contents::

Introduction

Constructor

Properties

Code Implement

Code File

Conclusion



Introduction:

InputChip is a material widget in a flutter that addresses a mind-boggling snippet of data in a conservative structure. Flutter gives a widget called InputChip which permits us to add an input chip to our application.

The input chip by default is disabled. We can empower it by setting onSelected. We can give a label, and leading and trailing symbols to it. Different kinds of chips are Chip, ChoiceChip, ActionChip, and FilterChip.

Demo Module ::

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

Constructor:

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

To make an Input chip in the flutter we need to utilize the constructor of the InputChip class given by the flutter.

const InputChip({
Key? key,
this.avatar,
required this.label,
this.labelStyle,
this.labelPadding,
this.selected = false,
this.isEnabled = true,
this.onSelected,
this.deleteIcon,
this.onDeleted,
this.deleteIconColor,
this.deleteButtonTooltipMessage,
this.onPressed,
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(),
@Deprecated(
'Migrate to deleteButtonTooltipMessage. '
'This feature was deprecated after v2.10.0-0.3.pre.'
)
this.useDeleteButtonTooltip = true,
})

One required property for the InputChip widget is the label property. The label can be any widget generally a text widget. To utilize the InputChip widget we need to furnish this property with a value.

Properties:

There are some properties of InputChip are:

  • > selected — This property is utilized to set the chip’s state to be chosen or unselected. It takes a boolean value setting that truly will make the chip chosen and false will make the chip unselected.
  • > onSelected — This property is utilized to update the selected or unselected state of the Input chip and perform some actions when the chip is selected or unselected.
  • > isEnabled — This property is utilized to enable or disable the input chip. It takes a boolean value. By default the value is true. Regardless of whether we set this property to true, we need to set one of the callbacks onSelected, onDelete, or onPressed to enable the button.
  • > disabledcolor — This property is utilized to apply a color to the inputChip when the chip is disabled we will utilize this property. So to disable the button I’m eliminating every one of the callbacks.
  • > showCheckmark — This property is utilized to show/hide away the check mark that seems when we select the chip. It takes a boolean value.
  • > pressElevation — This property is utilized to change the amount of elevation we want to apply when we press the 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 Inputchip. The ItemModel class will have three boundaries label, color, and isSelected. The label will hold the mark of the chip, the color will hold the backgroundColor and isSelected will hold the chosen or unselected condition of the Input chip.

import 'dart:ui';

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

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

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> _chips = [
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),
];

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 and its children were itemsChips() method.

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

Now we will deeply define itemsChips() method are:

This method was on the list of widgets. We will add the InputChip widget. In this widget, we will add an avatar, label, backgroundColor, selected, onDeleted, onSelected, and then return chips.

List<Widget> itemsChips() {
List<Widget> chips = [];
for (int i = 0; i < _chips.length; i++) {
Widget item = Padding(
padding: const EdgeInsets.only(left: 10, right: 5),
child: InputChip(
avatar: CircleAvatar(
backgroundColor: Colors.white,
child: Text(_chips[i].label[0].toUpperCase()),
),
label: Text(_chips[i].label),
labelStyle: const TextStyle(color: Colors.white),
backgroundColor: _chips[i].color,
selected: _chips[i].isSelected,
onDeleted: () {
setState(() {
_chips.removeAt(i);
});
},
onSelected: (bool value) {
setState(() {
_chips[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_input_chip_demo/item_model.dart';
import 'package:flutter_input_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.red,
),
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> {
final List<ItemModel> _chips = [
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(
backgroundColor: Colors.grey[200],
appBar: AppBar(
title: const Text("Flutter Input Chip Demo"),
centerTitle: true,
automaticallyImplyLeading: false,
backgroundColor: Colors.orangeAccent,
),
body: Center(
child: Column(
children: [
Image.asset(
"assets/logo.png",
height: 300,
width: 350,
),
Wrap(direction: Axis.horizontal, children: itemsChips()),
],
)),
);
}

List<Widget> itemsChips() {
List<Widget> chips = [];
for (int i = 0; i < _chips.length; i++) {
Widget item = Padding(
padding: const EdgeInsets.only(left: 10, right: 5),
child: InputChip(
avatar: CircleAvatar(
backgroundColor: Colors.white,
child: Text(_chips[i].label[0].toUpperCase()),
),
label: Text(_chips[i].label),
labelStyle: const TextStyle(color: Colors.white),
backgroundColor: _chips[i].color,
selected: _chips[i].isSelected,
onDeleted: () {
setState(() {
_chips.removeAt(i);
});
},
onSelected: (bool value) {
setState(() {
_chips[i].isSelected = value;
});
},
),
);
chips.add(item);
}
return chips;
}
}

Conclusion:

In the article, I have explained the Input Chip basic structure in a flutter; you can modify this code according to your choice. This was a small introduction to Input 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 Input Chip in your flutter projectsWe will show you what the Introduction is and what are the construction and properties of the Input Chip, and make a demo program for working with Input 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! 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.

Related: Choice Chip In Flutter

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