flutter filterchip widget button controls

What is the Flutter FilterChip Widget and how to use it

What is the Flutter FilterChip Widget

The Flutter FilterChip widget is a material design component that is used to display a set of tags or labels that can be used to filter content in your app. It is similar to the ChoiceChip widget, but instead of selecting a single option, you can select multiple options at the same time.

Each FilterChip widget consists of a label and an optional icon that can be used to represent the tag. When the user taps on a FilterChip, it becomes selected and the background colour changes to indicate that it is active. The FilterChip widget also provides an onSelected callback that is called when the user selects or deselects a chip, allowing you to update your app’s state accordingly.

FilterChip widgets are often used in conjunction with a list or grid of items that can be filtered by the selected tags. For example, if you have a list of products, you could use FilterChip widgets to allow the user to filter by category, brand, or price range.

What is the difference between Chip and FilterChip widget

The Flutter Chip widget and the FilterChip widget are both material design components used to display information or actions in your app, but they have some key differences.

The Chip widget is a basic component that displays a piece of information, such as a tag or a contact, and can also have an optional avatar icon. The Chip widget can also be used to represent a complex entity with multiple attributes, such as a user profile. The user cannot select or interact with the Chip, it is simply for display purposes.

On the other hand, the FilterChip widget is used for filtering content in your app. It allows the user to select multiple options at once from a set of tags or labels. When a FilterChip is selected, it becomes active and changes colour to indicate that it is selected. The FilterChip can also be used to represent a complex entity with multiple attributes, but its primary purpose is for filtering.

Another difference between the two widgets is that the Chip widget does not have an onSelected callback, whereas the FilterChip widget does. This means that the FilterChip widget can be used to update the app’s state when a filter is selected or deselected.

In summary, the Chip widget is a basic component for displaying information, while the FilterChip widget is used for filtering content in your app by allowing the user to select multiple options at once. The FilterChip widget also provides an onSelected callback for updating the app’s state.

Where the Flutter FilterChip widget can be used

The Flutter FilterChip widget is a versatile component that can be used in a variety of ways in your app. Here are a few of the most common usages of the FilterChip widget:

  1. Filter options: One of the most common uses of the FilterChip widget is to display filter options. You can use chips to represent different categories or tags and allow users to select one or more options to filter a list of results.
  2. Filtering content: The FilterChip widget is often used to filter content in a list or grid. For example, if you have a list of products, you could use FilterChip widgets to allow the user to filter by category, brand, or price range.
  3. Selecting multiple options: The FilterChip widget can be used to allow the user to select multiple options at once from a set of choices. For example, if you have a survey app, you could use FilterChip widgets to allow the user to select multiple answers from a list of options.
  4. Custom controls: The FilterChip widget can be customized to provide a unique user experience. For example, you could use FilterChip widgets to create a custom slider or to allow the user to adjust a value within a specific range.
  5. Tagging: The FilterChip widget can also be used for tagging content. For example, if you have a note-taking app, you could use FilterChip widgets to allow the user to tag their notes with keywords or topics.

FilterChip widget as a Button in Flutter

Here is an example of how to use the Flutter FilterChip widget as a button:

bool _isSelected = false;

@override
Widget build(BuildContext context) {

return Scaffold(
appBar: AppBar(
title: Text('flutterassets.com'),
),
body: Container(
alignment: Alignment.topCenter,
padding: const EdgeInsets.all(8.0),
child: FilterChip(
label: Text('Click me'),
selected: _isSelected,
onSelected: (isSelected) {
setState(() {
_isSelected = isSelected;
});
},
selectedColor: Colors.blue,
backgroundColor: Colors.grey[300],
)
),
);
}
flutter filterchip button

In this example, we create a FilterChip with a label that says “Click me”. We set the initial selected state of the chip to _isSelected, which is initially false. We also define an onSelected callback function that will be called when the chip is selected or unselected. In the onSelected function, we update the _isSelected variable to reflect the new selected state of the chip.

Finally, we set the selectedColor property to Colors.blue to indicate the color to use when the chip is selected, and we set the backgroundColor property to Colors.grey[300] to give the chip a gray background.

This FilterChip behaves like a button, as the user can click on it to select or unselect it.

How to disable the FilterChip widget after pressed

To disable a Flutter FilterChip Widget after it has been pressed, you can use a boolean variable to store the state of the FilterChip. You can use the onSelected callback function to handle the FilterChip selection event and update the state of the boolean variable to disable the FilterChip.

First, you can create a boolean variable to store the state of the FilterChip, and set it to false initially.

Then, you can use the FilterChip Widget with its selected property set to the boolean variable you created, so that the FilterChip will reflect the current state.

You can use the onSelected callback function to handle the FilterChip selection event. Within the onSelected event handler, you can use the setState() method to update the state of the boolean variable to true, which will disable the FilterChip.

Here’s an example code snippet:

bool _isDisabled = false;

@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('flutterassets.com'),
),
body: Container(
alignment: Alignment.topCenter,
padding: const EdgeInsets.all(8.0),
child: FilterChip(
showCheckmark: false,
label: _isDisabled ? Text('Disabled') : Text('Click me'),
selected: _isDisabled,
avatar: _isDisabled ? Icon(Icons.close) : null,
onSelected: _isDisabled ? null : (isSelected) {
setState(() {
_isDisabled = true;
});
print('Pressed');
},
selectedColor: Colors.grey[300],
backgroundColor: Colors.blue,
)
),
);
}
flutter filterchip disable

In this example, the FilterChip will be enabled initially with the label “Click me”. When the FilterChip is selected, the _isDisabled boolean variable will be set to true using setState(), which will disable the FilterChip. The label and avatar of the FilterChip will also change to reflect the disabled state.

Use the Flutter FilterChip widget to filter options

Here’s an example of how to use the Flutter Chip widget as a filter option:

List<String> _filters = ['All', 'Fruit', 'Vegetables', 'Meat'];

List<String> _selectedFilters = [];

_selectFilter(String filter) {
setState(() {
if (_selectedFilters.contains(filter)) {
_selectedFilters.remove(filter);
} else {
_selectedFilters.add(filter);
}
});
}

@override
Widget build(BuildContext context) {

return Scaffold(
appBar: AppBar(
title: Text('flutterassets.com'),
),
body: Container(
padding: EdgeInsets.all(20),
child: Wrap(
spacing: 8.0,
children: _filters.map((filter) {
return FilterChip(
label: Text(filter),
selected: _selectedFilters.contains(filter),
onSelected: (selected) {
_selectFilter(filter);
},
);
}).toList(),
),
),
);
}
flutter chip widget filter options

In this example, the _filters list contains the different filter options we want to display and the _selectedFilters list keeps track of which filters the user has selected.

The _selectFilter function is called when the user selects or deselects a filter. It updates the _selectedFilters list accordingly.

In the build method, we use a Wrap widget to display the filter options as a series of chips with some spacing between them. We use the map method to iterate over the _filters list and create a FilterChip widget for each filter option. The selected property of each chip is set based on whether the corresponding filter is included in the _selectedFilters list, and the onSelected property is set to call the _selectFilter function when the user selects or deselects the chip.

By using the Flutter Chip widget as a filter option, we can create a clear and intuitive interface that allows users to easily filter a list of results based on their preferences.

Another example of Selecting multiple options with the Flutter FilterChip widget

Here is another example of how to use the Flutter FilterChip widget to allow the user to select multiple options:

List<String> selectedAnswers = [];
final List<String> answers = [ 'Option 1', 'Option 2', 'Option 3', 'Option 4', ];

@override
Widget build(BuildContext context) {

return Scaffold(
appBar: AppBar(
title: Text('flutterassets.com'),
),
body: Center(
child: Container(
alignment: Alignment.topCenter,
padding: const EdgeInsets.all(8.0),
child: Wrap(
spacing: 8.0,
runSpacing: 4.0,
children: List<Widget>.generate(
answers.length,
(int index) {
return FilterChip(
label: Text(answers[index]),
selected: selectedAnswers.contains(answers[index]),
onSelected: (bool selected) {
setState(() {
if (selected) {
selectedAnswers.add(answers[index]);
} else {
selectedAnswers.remove(answers[index]);
}
});
},
);
},
).toList(),
),
),
),
);
}
flutter choicechip selecting multiple option

In this example, we use a list of possible answers to a survey question. We use the FilterChip widget to display each possible answer as a chip. When the user taps on a chip, it toggles its selected state. We keep track of which answers are selected in a list called selectedAnswers. We use a Wrap widget to display the FilterChips in a row and wrap them to the next line if there’s not enough space.

You could modify this example to suit your needs, for example by changing the list of answers or by using the selectedAnswers list to filter the survey results.

Selecting multiple options with the Flutter FilterChip with a Text output

Here is an example of how to use the Flutter FilterChip widget to allow the user to select multiple options:

List<String> selectedOptions = [];
final List<String> options = ['Option 1', 'Option 2', 'Option 3', 'Option 4'];

@override
Widget build(BuildContext context) {

return Scaffold(
appBar: AppBar(
title: Text('flutterassets.com'),
),
body: Center(
child: Container(
alignment: Alignment.topCenter,
padding: const EdgeInsets.all(8.0),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
SizedBox(height: 16.0),
Text(
'Select all that apply:',
style: TextStyle(fontSize: 18.0, fontWeight: FontWeight.bold),
),
SizedBox(height: 16.0),
Wrap(
spacing: 8.0,
children: List<Widget>.generate(options.length, (int index) {
return FilterChip(
label: Text(options[index]),
selected: selectedOptions.contains(options[index]),
onSelected: (bool selected) {
setState(() {
if (selected) {
selectedOptions.add(options[index]);
} else {
selectedOptions.remove(options[index]);
}
});
},
);
}),
),
SizedBox(height: 16.0),
Text(
'Selected options: ${selectedOptions.join(", ")}',
style: TextStyle(fontSize: 18.0),
),
],
),
),
),
);
}
flutter filterchip widget select multiple options

In this example, we have a code that displays a list of options using FilterChip widgets. We also have a selectedOptions list to keep track of the options that the user has selected.

When the user taps on a FilterChip, we update the selectedOptions list to add or remove the selected option. We use the selected property to set the initial selection state of the FilterChip, and the onSelected callback to handle the user’s selection.

We also display the selected options in a Text widget at the bottom of the page using the join method to display them as a comma-separated list.

With this implementation, the user can select multiple options from the list by tapping on the corresponding FilterChips, and their selections will be reflected in the selectedOptions list.

Use the Flutter FilterChip widget to Filtering content

Here’s a revised example that displays all products within a selected category using the FilterChip widget:

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget {

  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      title: 'Flutter Demo',
      theme: ThemeData(
        primarySwatch: Colors.blue,
      ),
      home: MyHomePage(),
    );
  }
}

class MyHomePage extends StatefulWidget {

  @override
  State<MyHomePage> createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage>{

  // Define a list of products
  List<Product> products = [
    Product(name: 'Product 1', category: 'Category A'),
    Product(name: 'Product 2', category: 'Category B'),
    Product(name: 'Product 3', category: 'Category C'),
    Product(name: 'Product 4', category: 'Category A'),
    Product(name: 'Product 5', category: 'Category B'),
    Product(name: 'Product 6', category: 'Category C'),
  ];

  // Define a list of categories
  List<String> categories = ['All', 'Category A', 'Category B', 'Category C'];

  // Define a variable to store the selected category
  String selectedCategory = 'All';

  @override
  Widget build(BuildContext context) {

    return Scaffold(
      appBar: AppBar(
        title: Text('flutterassets.com'),
      ),
      body: Container(
        alignment: Alignment.topCenter,
        padding: const EdgeInsets.all(8.0),
        child: Column(
          children: [
            // Create a row of FilterChip widgets to filter by category
            Row(
              children: categories.map((category) {
                return FilterChip(
                  label: Text(category),
                  selected: selectedCategory == category,
                  onSelected: (isSelected) {
                    setState(() {
                      selectedCategory = isSelected ? category : 'All';
                    });
                  },
                );
              }).toList(),
            ),
            // Create a list of products filtered by category
            Expanded(
              child: ListView.builder(
                itemCount: products.length,
                itemBuilder: (BuildContext context, int index) {
                  if (selectedCategory == 'All' ||
                      selectedCategory == products[index].category) {
                    return ListTile(
                      title: Text(products[index].name),
                    );
                  } else {
                    return SizedBox.shrink();
                  }
                },
              ),
            ),
          ],
        ),
      ),
    );
  }
}

class Product {
  final String name;
  final String category;

  Product({required this.name, required this.category});
}
ezgif 3 71b159ced3

In this example, we have a list of Product objects with a name and category attribute. We also have a list of categories that we will use to display as filter options.

We display the categories using Wrap widget and FilterChip widget for each category. We use the selected property to determine if a filter chip is selected, and update the selectedCategory variable when a chip is selected.

In the ListView.builder widget, we filter the products based on the selected category. If no category is selected, we display all products, otherwise, we only display the products with the selected category. We achieve this using an if statement that checks if selectedCategory is empty or if it matches the category of the current product.

This example demonstrates how the FilterChip widget can be used to filter content in a list based on user selection.

Use the Flutter FilterChip widget as custom controls (Flutter FilterChip as a Button)

Here is an example of how you could use the FilterChip widget as a custom control:

double _value = 0.0;

void _handleValueChanged(double newValue) {
setState(() {
_value = newValue;
});
}

@override
Widget build(BuildContext context) {

return Scaffold(
appBar: AppBar(
title: Text('flutterassets.com'),
),
body: Container(
alignment: Alignment.topCenter,
padding: const EdgeInsets.all(8.0),
child: Column(
children: [
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
FilterChip(
label: Text('\$0'),
selected: _value == 0.0,
onSelected: (isSelected) {
_handleValueChanged(0.0);
},
),
FilterChip(
label: Text('\$10'),
selected: _value == 10.0,
onSelected: (isSelected) {
_handleValueChanged(10.0);
},
),
FilterChip(
label: Text('\$20'),
selected: _value == 20.0,
onSelected: (isSelected) {
_handleValueChanged(20.0);
},
),
FilterChip(
label: Text('\$30'),
selected: _value == 30.0,
onSelected: (isSelected) {
_handleValueChanged(30.0);
},
),
],
),
),
Padding(
padding: const EdgeInsets.symmetric(horizontal: 16.0, vertical: 16.0),
child: LinearProgressIndicator(
value: _value / 30.0,
),
),
Text('\$$_value')
],
)
),
);
}
flutter filterchip widget button controls

In this example, we’ve created a custom Slider widget that uses FilterChip widgets to allow the user to select a value from a specific range. The _value variable keeps track of the current value, and the _handleValueChanged method is called whenever a FilterChip is selected to update the _value.

The CustomSlider widget contains a row of FilterChip widgets representing different values in the range, and a LinearProgressIndicator that shows the current value selected by the user. Finally, the current value is displayed using a Text widget.

Use the Flutter FilterChip widget as Tags

Here’s an example of how to use the FilterChip widget with tagging:

final List<String> _tags = [
'Personal',
'Work',
'Ideas',
'Shopping',
'Travel',
'Recipes',
'Fitness',
'Books',
'Movies',
];
final List<String> _selectedTags = [];

void _toggleTag(String tag) {
setState(() {
if (_selectedTags.contains(tag)) {
_selectedTags.remove(tag);
} else {
_selectedTags.add(tag);
}
});
}

@override
Widget build(BuildContext context) {

return Scaffold(
appBar: AppBar(
title: Text('flutterassets.com'),
),
body: Container(
alignment: Alignment.topCenter,
padding: const EdgeInsets.all(8.0),
child: Wrap(
spacing: 8.0,
children: _tags.map((tag) {
return FilterChip(
label: Text(tag),
selected: _selectedTags.contains(tag),
onSelected: (isSelected) {
_toggleTag(tag);
print('${_selectedTags}');
},
);
}).toList(),
)
),
);
}
flutter filterchip widget tagging

In this example, we have a NoteTags widget that displays a list of tags. The _tags list contains a list of all the available tags that the user can choose from, and the _selectedTags list contains the tags that the user has selected.

The _toggleTag method is called whenever a FilterChip is selected or unselected. It checks whether the selected tag is already in the _selectedTags list, and either adds it or removes it based on the current state.

The Wrap widget is used to display the FilterChips in a horizontal layout. We loop through the _tags list and create a FilterChip for each tag, passing in the tag’s label as the label property, whether it is currently selected based on whether it is in the _selectedTags list, and the _toggleTag method as the onSelected property.

This allows the user to select multiple tags by tapping on each FilterChip, and the selected tags will be highlighted with a different colour.