skip to Main Content

i have list string like this :
List<String> alphabet = [a,b,c];

then i add same string like : alphabet.add(a);

the result is [a,b,c,a]

the question is, How do I make sure the values ​​in the string list
remain the same [a,b,c] because the value a already exists in the string list

2

Answers


  1. The easiest way is to check if the character is already contained before adding it.

    if(!alphabet.contains(newChar)){
        alphabet.add(newChar);
    }
    
    Login or Signup to reply.
  2. Use Set (https://api.dart.dev/stable/3.1.3/dart-core/Set-class.html):

    Set<String> alphabet = Set();
    alphabet.add("a");
    alphabet.add("a"); // Won't be added
    alphabet.add("b");
    
    print(alphabet);
    
    // Result: {a, b}
    

    Sets are like lists but automatically ignores duplicates, the best (and suggested) solution for your needs.

    Also, you can convert it to List using alphabet.toList();

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search