How to Remove Duplicates from List to Make Unique in Dart/Flutter

In this example, we are going to show you how to make an array List unique by removing duplicate elements in Dart or Flutter. In many cases, you may need to make your Dart list unique. See the example below:

Read This Also: How to Sort List on Alphabetical Order in Dart/Flutter

List<String> countries = [
    "Nepal", 
    "Nepal", 
    "USA",
    "Canada",
    "Canada",
    "China",
    "Russia",
];

var seen = Set<String>();
List<String> uniquelist = countries.where((country) => seen.add(country)).toList();
print(uniquelist);
//output:  [Nepal, USA, Canada, China, Russia]

This is the best way to make List unique, it will keep the order of List and it can be used to remove duplicates from List of objects by its property.

List<int> numbers = [1,2,1,3,3,5,4,5];

var seenint = Set<String>();
List<int> uniquenum = numbers.where((numone) => seen.add(numone.toString())).toList();
print(uniquenum);
//output: [1, 2, 3, 5, 4]

import 'package:flutter/material.dart';

void main() {
  runApp( 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 = [
        "Nepal", 
        "Nepal", 
        "USA",
        "Canada",
        "Canada",
        "China",
        "Russia",
    ];

    var seen = Set<String>();
    List<String> uniquelist = countries.where((country) => seen.add(country)).toList();
    print(uniquelist);
    //output:  [Nepal, USA, Canada, China, Russia]

    return Scaffold(
         appBar: AppBar(
            title: Text("Remove Duplicates from List"),
            backgroundColor: Colors.redAccent,
         ),
          body: Container(
             alignment: Alignment.center,
             padding: EdgeInsets.all(20),
             child: Column(
               children:uniquelist.map((cone){
                  return Container(
                    child: Card(
                       child:Container( 
                         width: double.infinity,
                         padding: EdgeInsets.all(15),
                         child: Text(cone, style: TextStyle(fontSize: 18))),
                       ),
                  );
               }).toList(),
             ),
          )
      );
  }
} 

In this way, you can remove duplicate elements to make a unique List array in Dart or Flutter.

No any Comments on this Article


Please Wait...