Flutter – Filter a List Using Some Condition
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), ), ], ), ), ); } } |
Contact Us