DART/FLUTTER - Check if a class value has already been instantiated

Viewed 59

I have a class with the following attributes in Dart

class StartValue {
    final int id;
    final String firstName;
    final String lastName;

    StartValue({this.id, this.firstName, this.lastName})
}

and Ill initiate that classe with the values:

StartValue(
    id: 1,
    firstName: 'First',
    lastName: 'LastName'
)

The question is what kind of validation i need to do to never instance a class StartValue with the NAME = 'First' again? Assuming I can only instantiate the class once with firstName = 'First'.

How do I do an instance validation to verify that each instance does not contain the firstName = "First" ?

I have to do something like:

StartValues.contains("First")

Keep in mind that I have almost 1000 classes instantiated, so I will have to check one by one if the value "First" contains in each class, this is my question

3 Answers

You have to iterate through every class to check if the firstName is taken, but I recommend using the == operator instead of .contains(). Why would you have 1000 instances? Can you put us in context?

Use a class-static Set of all ids seen so far. This will be quick to identify whether an item has already been generated.

Something like:

class Person {
  final int id;
  final String name;

  static var seenIds = <int>{};

  Person({
    required this.id,
    required this.name,
  }) {
    if (!seenIds.add(id)) throw ArgumentError('id $id already seen');
  }
}

Keeping thousands of instances / names in memory is bad design as they are way too many instances / names you don't need at that moment. You go for local sql database like sqflite or you go for cloud database like Cloud Firestore to fetch the user you need and validate it.

If you still want to do it in-memory you can use a factory constructor, a private constructor and a static HashSet to check user instances.

If you need explanation then comment below. Full code example:

import 'dart:collection';

class Person {
  final int id;
  final String firstName;
  final String lastName;

  static HashSet<String> allNames = HashSet<String>();

  factory Person({
    required int id,
    required String firstName,
    required String lastName,
  }) {
    if (!allNames.add(firstName)) {
      throw ArgumentError("Person with firstname $firstName already exists");
    }
    return Person._(id: id, firstName: firstName, lastName: lastName);
  }

  Person._({
    required this.id, 
    required this.firstName, 
    required this.lastName
  });
}
Related