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
Non-linear Components
In electrical circuits, Non-linear Components are electronic devices that need an external power source to operate actively. Non-Linear Components are those that are changed with respect to the voltage and current. Elements that do not follow ohm's law are called Non-linear Components. Non-linear Co
11 min read
Steady State Response
In this article, we are going to discuss the steady-state response. We will see what is steady state response in Time domain analysis. We will then discuss some of the standard test signals used in finding the response of a response. We also discuss the first-order response for different signals. We
9 min read
Use Case Diagram - Unified Modeling Language (UML)
A Use Case Diagram in Unified Modeling Language (UML) is a visual representation that illustrates the interactions between users (actors) and a system. It captures the functional requirements of a system, showing how different users engage with various use cases, or specific functionalities, within
9 min read
Half Wave Rectifier
A Half-wave rectifier is an electronic device that is used to convert Alternating current (AC) to Direct current (DC). A half-wave rectifier allows either a positive or negative half-cycle of AC to pass and blocks the other half-cycle. Half-wave rectifier selectively allows only one half-cycle of th
15 min read
Flutter Tutorial
This Flutter Tutorial is specifically designed for beginners and experienced professionals. It covers both the basics and advanced concepts of the Flutter framework.Flutter is Googleâs mobile SDK that builds native Android and iOS apps from a single codebase. It was developed in December 2017. When
7 min read
Top 8 Software Development Life Cycle (SDLC) Models used in Industry
Software development models are various processes or methods that are chosen for project development depending on the objectives and goals of the project. Many development life cycle models have been developed to achieve various essential objectives. Models specify the various steps of the process a
9 min read
What is Agile Methodology?
The Agile methodology is a proper way of managing the project with breaking them into smaller phases which is iteration. It basically focus on flexibility of the project which we can change and improve the team work regularly as per requirements.Table of ContentWhat is Agile?What is the Agile Method
14 min read
How to Download and Install the Google Play Store
The Google Play Store is the heartbeat of your Android experienceâhome to millions of apps, games, and updates that keep your device functional, fun, and secure. But what if your phone or tablet doesnât have it pre-installed?In this step-by-step guide, youâll learn how to safely download and install
6 min read
IEEE 802.11 Architecture
The IEEE 802.11 standard, commonly known as Wi-Fi, outlines the architecture and defines the MAC and physical layer specifications for wireless LANs (WLANs). Wi-Fi uses high-frequency radio waves instead of cables for connecting the devices in LAN. Given the mobility of WLAN nodes, they can move unr
9 min read
Transaction in DBMS
In a Database Management System (DBMS), a transaction is a sequence of operations performed as a single logical unit of work. These operations may involve reading, writing, updating, or deleting data in the database. A transaction is considered complete only if all its operations are successfully ex
10 min read