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

Time:09-12

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

CodePudding user response:

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');
  }
}

CodePudding user response:

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?

  • Related