Flutter - Filter a List Using Some Condition
Last Updated :
28 Apr, 2025
In Flutter, the where() method can be used on a list to filter its elements based on a specified condition. To demonstrate this let's make a Flutter app that will contain a List of products having name, category and price. Then we create a TextView named a Filtered list by price when the user enters some price the app will fetch the product with the mentioned price from the List of available products. A sample video is attached 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: Import the Package
First of all import material.dart file.
import 'package:flutter/material.dart';
Step 3: Execute the main Method
Here the execution of our app starts.
Dart
void main() {
runApp(MyApp());
}
Step 4: Create MyApp Class
In this class we are going to implement the MaterialApp , here we are also set the Theme of our App.
Dart
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: ListFilter(),
theme: ThemeData(
// Set the app's primary theme color
primarySwatch: Colors.green,
),
debugShowCheckedModeBanner: false,
);
}
}
Step 5: Creating an ListFilter Class
In this class we are going to create a list of product and impement a method using where() to filter the list based on the price entered by the user. Comments are added for better understanding.
Creating an list of product:
final List<Product> products = [
Product(name: 'Product 1', price: 10.0, category: 'Category A'),
Product(name: 'Product 2', price: 25.0, category: 'Category B'),
Product(name: 'Product 3', price: 15.0, category: 'Category A'),
Product(name: 'Product 4', price: 30.0, category: 'Category C'),
Product(name: 'Product 5', price: 20.0, category: 'Category A'),
];
Creating an method for filter the list based on the user entered price using where():
// Function to filter products by price
void filterProductsByPrice(String price) {
setState(() {
filterPrice = price;
// Use the 'where' method to filter products by price
filteredProducts = products
.where((product) =>
product.price.toStringAsFixed(2).contains(filterPrice))
.toList();
});
}
Funtion to build a product card for displaying it:
// Function to build a product card
Widget _buildProductCard(Product product, BuildContext context) {
return Card(
elevation: 5,
margin: EdgeInsets.symmetric(vertical: 10, horizontal: 20),
child: Padding(
padding: EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
product.name,
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
SizedBox(height: 5),
Text(
'Price: Rs.${product.price.toStringAsFixed(2)}',
style: TextStyle(fontSize: 16, color: Colors.green),
),
SizedBox(height: 5),
Text(
'Category: ${product.category}',
style: TextStyle(fontSize: 16, color: Colors.blue),
),
],
),
),
);
}
Dart
class ListFilter extends StatefulWidget {
@override
_ListFilterState createState() => _ListFilterState();
}
class _ListFilterState extends State<ListFilter> {
final List<Product> products = [
Product(name: 'Product 1', price: 10.0, category: 'Category A'),
Product(name: 'Product 2', price: 25.0, category: 'Category B'),
Product(name: 'Product 3', price: 15.0, category: 'Category A'),
Product(name: 'Product 4', price: 30.0, category: 'Category C'),
Product(name: 'Product 5', price: 20.0, category: 'Category A'),
];
String filterPrice = '';
List<Product> filteredProducts = [];
@override
void initState() {
// Initialize the filtered
// list with all products
filteredProducts = products;
super.initState();
}
// Function to filter products by price
void filterProductsByPrice(String price) {
setState(() {
filterPrice = price;
// Use the 'where' method to
// filter products by price
filteredProducts = products
.where((product) =>
product.price.toStringAsFixed(2).contains(filterPrice))
.toList();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Product Filter App'),
),
body: SingleChildScrollView(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
// Text input field for price filtering
Padding(
padding: const EdgeInsets.all(16.0),
child: TextField(
decoration: InputDecoration(labelText: 'Filter by Price'),
// Call the filtering
// function on text change
onChanged: filterProductsByPrice,
),
),
Text(
'Filtered Products',
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
),
SizedBox(height: 10),
for (var product in filteredProducts)
_buildProductCard(product, context),
],
),
),
),
);
}
// Function to build a product card
Widget _buildProductCard(Product product, BuildContext context) {
return Card(
elevation: 5,
margin: EdgeInsets.symmetric(vertical: 10, horizontal: 20),
child: Padding(
padding: EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
product.name,
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
SizedBox(height: 5),
Text(
'Price: Rs.${product.price.toStringAsFixed(2)}',
style: TextStyle(fontSize: 16, color: Colors.green),
),
SizedBox(height: 5),
Text(
'Category: ${product.category}',
style: TextStyle(fontSize: 16, color: Colors.blue),
),
],
),
),
);
}
}
Step 6: Creating an Product Class
This class contains 3 fields named as name(type-String ),price(type - double),category(type - String) and a constructor to intialize these fields.
Dart
class Product {
final String name;
final double price;
final String category;
Product({required this.name, required this.price, required this.category});
}
Here is the full Code of main.dart file:
Dart
import 'package:flutter/material.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
@override
Widget build(BuildContext context) {
return MaterialApp(
home: ListFilter(),
theme: ThemeData(
// Set the app's primary theme color
primarySwatch: Colors.green,
),
debugShowCheckedModeBanner: false,
);
}
}
class Product {
final String name;
final double price;
final String category;
Product({required this.name, required this.price, required this.category});
}
class ListFilter extends StatefulWidget {
@override
_ListFilterState createState() => _ListFilterState();
}
class _ListFilterState extends State<ListFilter> {
final List<Product> products = [
Product(name: 'Product 1', price: 10.0, category: 'Category A'),
Product(name: 'Product 2', price: 25.0, category: 'Category B'),
Product(name: 'Product 3', price: 15.0, category: 'Category A'),
Product(name: 'Product 4', price: 30.0, category: 'Category C'),
Product(name: 'Product 5', price: 20.0, category: 'Category A'),
];
String filterPrice = '';
List<Product> filteredProducts = [];
@override
void initState() {
// Initialize the filtered
// list with all products
filteredProducts = products;
super.initState();
}
// Function to filter products by price
void filterProductsByPrice(String price) {
setState(() {
filterPrice = price;
// Use the 'where' method to
// filter products by price
filteredProducts = products
.where((product) =>
product.price.toStringAsFixed(2).contains(filterPrice))
.toList();
});
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Product Filter App'),
),
body: SingleChildScrollView(
child: Center(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
children: <Widget>[
// Text input field for price filtering
Padding(
padding: const EdgeInsets.all(16.0),
child: TextField(
decoration: InputDecoration(labelText: 'Filter by Price'),
// Call the filtering function
// on text change
onChanged: filterProductsByPrice,
),
),
Text(
'Filtered Products',
style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
),
SizedBox(height: 10),
for (var product in filteredProducts)
_buildProductCard(product, context),
],
),
),
),
);
}
// Function to build a product card
Widget _buildProductCard(Product product, BuildContext context) {
return Card(
elevation: 5,
margin: EdgeInsets.symmetric(vertical: 10, horizontal: 20),
child: Padding(
padding: EdgeInsets.all(20),
child: Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: <Widget>[
Text(
product.name,
style: TextStyle(fontSize: 18, fontWeight: FontWeight.bold),
),
SizedBox(height: 5),
Text(
'Price: Rs.${product.price.toStringAsFixed(2)}',
style: TextStyle(fontSize: 16, color: Colors.green),
),
SizedBox(height: 5),
Text(
'Category: ${product.category}',
style: TextStyle(fontSize: 16, color: Colors.blue),
),
],
),
),
);
}
}
Output:
Similar Reads
Face Detection in Flutter using Firebase ML Kit Face detection is a technique by which we can locate the human faces in the image given. Face detection is used in many places nowadays, especially websites hosting images like Picasa, Photobucket, and Facebook. The automatic tagging feature adds a new dimension to sharing pictures among the people
5 min read
Recipe Finder Application in Flutter This app will display a list of recipes in a card format, each containing the recipe title, a rating, the cooking time, and a thumbnail image to give users a visual preview. The app is dynamic and flexible, allowing you to easily update the recipe list or modify the UI as needed.By the end of this t
5 min read
How to use Conditional Statement on Widget in Flutter? Handling conditions is not too much difficult in Flutter. We can easily write our conditions based on the requirements which we are acquiring from our application. Let's work on conditions in flutter Apps. In this article, we'll talk about conditions and how we handle elements or widgets by using co
2 min read
Flutter - Animate Items in List Using AnimatedList The AnimatedList widget in Flutter is used to create a list that automatically animates changes to its items. It's particularly useful when you want to add or remove items from a list with smooth animations. In this article, we are going to see how the list is animated when an item is deleted or add
5 min read
Flutter - Select Single and Multiple Files From Device We will explore how to select single, or multiple files from our device with different conditions. Sometimes it happens that we want to select only a single type of file or with a fixed extension. If you are looking for the same just read the article till the end. Step By Step Implementation 1. Crea
6 min read