Skip to main content

Flutter Dart Remove Duplicate Item From List Array

To remove duplicate items from List array we will use combination of 3 array list in dart. The method we will using to removed same items is List.where(). After removing duplicate items we will show the list into ListView widget.

Flutter Dart Remove Duplicate Item From List Array

1. Creating a String List with duplicate items inside it.
 List<String> fruitList = [
    "Apple", 
    "Apple", 
    "Banana",
    "Banana",
    "Coconut",
    "Cherry",
    "Banana",
    "Apple",
    "Cherry",
    "Coconut"
];
2. Creating a temporary empty growable list. We will use this list to temporary store list items.
 var tempList = <String>{};
3. Creating our final filtered list and remove items from OLD list with Where function.
 List<String> uniqueFruits = fruitList.where((fruit) => tempList.add(fruit)).toList();
Code Example:
void main() {
  
 List<String> fruitList = [
    "Apple", 
    "Apple", 
    "Banana",
    "Banana",
    "Coconut",
    "Cherry",
    "Banana",
    "Apple",
    "Cherry",
    "Coconut"
];

var tempList = <String>{};
  
List<String> uniqueFruits = fruitList.where((fruit) => tempList.add(fruit)).toList();

print(uniqueFruits);
  
}
Output:

Source code for main.dart file:

import 'dart:collection';

import 'package:flutter/material.dart';

void main() => runApp(App());

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

class MyApp extends StatefulWidget {
  const MyApp({super.key});

  @override
  MyAppState createState() => MyAppState();
}

class MyAppState extends State {
  @override
  void initState() {
    super.initState();

    uniqueFruits = fruitList.where((fruit) => tempList.add(fruit)).toList();
  }

  List<String> fruitList = [
    "Apple",
    "Apple",
    "Banana",
    "Banana",
    "Coconut",
    "Cherry",
    "Banana",
    "Apple",
    "Cherry",
    "Coconut"
  ];

  var tempList = <String>{};

  List<String> uniqueFruits = <String>[];

  getItem(item) {
    print(item);
  }

  @override
  Widget build(BuildContext context) {
    return ListView.builder(
        itemCount: uniqueFruits.length,
        itemBuilder: (BuildContext context, int index) {
          return Container(
            height: 48,
            margin: const EdgeInsets.all(3),
            color: Colors.teal,
            child: Center(
                child: InkWell(
                    onTap: () {
                      getItem(uniqueFruits[index]);
                    },
                    child: Text(
                      uniqueFruits[index],
                      style: const TextStyle(fontSize: 24, color: Colors.white),
                    ))),
          );
        });
  }
}
Screenshots:
Flutter Dart Remove Duplicate Item From List Array

Comments