Flutter – Choice Chip
Last Updated :
09 Nov, 2022
ChoiceChips represent a single choice from a set. Choice chips contain related descriptive text or categories. Choice chip can be used in selecting the categories and in filtering the data, Code going to be simple to implement, there is no need to add the package into your pubspec yaml file,
Syntax:
Dart
ChoiceChip(
padding: EdgeInsets.all(8),
label: Text( 'Item $index' ),
selectedColor: Colors.green,
selected: _value == index,
onSelected: ( bool selected) {
setState(() {
_value = selected ? index : null;
});
|
A sample video is given below to get an idea about what we are going to do in this article.
Step By Step Implementation
Step 1: Create a New Project in Android Studio
To set up Flutter Development on Android Studio please refer to Android Studio Setup for Flutter Development, and then create a new project in Android Studio please refer to Creating a Simple Application in Flutter.
Step 2: Now we have to create a stateful widget, that returns the MaterialApp, MaterialApp allows us to set the title of the app and theme, home …etc, In home property use scaffold widget, that will allow us to set the AppBar and body of the scaffold.
Dart
import 'package:flutter/material.dart' ;
void main() {
runApp(MyThreeOptions());
}
class MyThreeOptions extends StatefulWidget {
const MyThreeOptions({super.key});
@override
State<MyThreeOptions> createState() => _MyThreeOptionsState();
}
class _MyThreeOptionsState extends State<MyThreeOptions> {
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false ,
home: Scaffold(
appBar: AppBar(
title: Text( 'Flutter - Choice chip' ),
),
body:
),
);
}
}
|
Step 3: We are creating a list of choice chips by building a custom list, In which we can return the choice chip and give properties.
Code
Dart
import 'package:flutter/material.dart' ;
void main() {
runApp(MyThreeOptions());
}
class MyThreeOptions extends StatefulWidget {
const MyThreeOptions({super.key});
@override
State<MyThreeOptions> createState() => _MyThreeOptionsState();
}
class _MyThreeOptionsState extends State<MyThreeOptions> {
int ? _value = 1;
@override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false ,
home: Scaffold(
appBar: AppBar(
title: Text( 'Flutter - Choice chip' ),
),
body: Wrap(
children: List.generate(
3,
( int index) {
return ChoiceChip(
padding: EdgeInsets.all(8),
label: Text( 'Item $index' ),
selectedColor: Colors.green,
selected: _value == index,
onSelected: ( bool selected) {
setState(() {
_value = selected ? index : null;
});
},
);
},
).toList(),
),
),
);
}
}
|
Output:
Share your thoughts in the comments
Please Login to comment...