How to Filter List Array in Dart/Flutter

In this example, we are going to show you how to filter the List array with some value of conditions and get a filtered array in Dart or Flutter. See the example below:

List<String> countries = ["Canada", "Brazil", "USA", "Japan", "China","UK", "Uganda", "Uruguay"];

List<String> filter = [];
filter.addAll(countries);

filter.retainWhere((countryone){
    return countryone.toLowerCase().contains("U".toLowerCase());
    //you can add another filter conditions too
});
print(filter); //list of countries which contains 'U' on name
//output:  [USA, UK, Uganda, Uruguay]

list.retainWhere() deletes the array element if it doesn't satisfy the condition applied to it. You can use this same method to filter the List array of objects as well.

import 'package:flutter/material.dart';

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

class MyApp extends StatelessWidget{
  @override
  Widget build(BuildContext context) {
     return MaterialApp(
         home: Home()
      );
  }
}

class Home extends  StatefulWidget {
  @override
  State<Home> createState() => _HomeState();
}

class _HomeState extends State<Home> {
  @override
  Widget build(BuildContext context) {

    List<String> countries = ["Canada", "Brazil", "USA", "Japan", "China","UK", "Uganda", "Uruguay"];

    List<String> filter = [];
    filter.addAll(countries);

    filter.retainWhere((countryone){
       return countryone.toLowerCase().contains("U".toLowerCase());
       //you can add another filter conditions too
    });
    print(filter); //list of countries which contains 'U' on name
    //output:  [USA, UK, Uganda, Uruguay]

    return Scaffold(
         appBar: AppBar(
            title: Text("Filter Array in Dart"),
            backgroundColor: Colors.redAccent
         ),
          body: Container(
             margin: EdgeInsets.all(10),
             alignment: Alignment.topCenter,
             child: Column(
                 children: filter.map((countryone){
                     return Card(
                       child:ListTile(
                            title: Text(countryone)
                       )
                     );
                 }).toList(),
             ),
          )
    );
  } 
}

In this way, you can filter the List array in Dart/Flutter.

No any Comments on this Article


Please Wait...