Shakun's
Shakun's

Reputation: 364

List.contains not working with initialized List

Code are as follow:

  class GuestController extends GetxController {

  final _userDataController = Get.find<UserDataController>();


  List fixGuestList = List.filled(3, null, growable: false);
  List? guestList = _userDataController.userDataModel.value.totalGuest! // This list is filled via API

  // returns and empty index for fixGuestList
  int _returnIndex() {
    if (fixGuestList[0] == null) {
      return 0;
    } else if (fixGuestList[1] == null) {
      return 1;
    } else if (fixGuestList[2] == null) {
      return 2;
    }
    return 3;
  }

  // Add function
  void addToLane({required int index, required BuildContext context}) {
    if (fixGuestList.contains(guestList![index])) {
      ScaffoldMessenger.of(context).showSnackBar(_snackBar);
    } else {
      fixGuestList[_returnIndex()] = guestList![index];
      storageBox.write('FixGuestList', fixGuestList);
    }
    update();
  }

  //
  void onInitAssign() async {
    final _boxValue = storageBox.read('FixGuestList');

    if (_boxValue == null) {
      List fixGuestList = List.filled(3, null, growable: false);
    } else {
      fixGuestList = _boxValue;
    }
    update();
  }

  // OnInit Function
  @override
  void onInit() {
    onInitAssign();
    super.onInit();
  }
}

API Class:

class FirbaseAPI extends GetxController {
  
  
  
  @override
  void onInit() {
   userDataModel.bindStream(stream());
    super.onInit();
  }
  
   // Stream User Model
  Rx<UserDataModel> userDataModel = UserDataModel().obs;

  // Stream
  Stream<UserDataModel> stream() {
    return FirebaseFirestore.instance
        .collection('users')
        .doc('userA')
        .snapshots()
        .map((ds) {
      var mapData = ds.data();

      UserDataModel extractedModel = UserDataModel.fromMap(mapData);
      return extractedModel;
    });
  }
}

Model Class:

class UserDataModel {
  String? clubName;
  List? totalGuest;

  UserDataModel({
    this.clubName,
    this.totalGuest,
  });

  factory UserDataModel.fromMap(dynamic fieldData) {
    return UserDataModel(
      totalGuest: fieldData['totalGuest'],
    );
  }
}

Upvotes: 0

Views: 309

Answers (1)

nvoigt
nvoigt

Reputation: 77324

contains uses operator equals (see here), commonly known as ==, to determine if something is equal.

To quote the documentation linked above:

The default behavior for all Objects is to return true if and only if this and other are the same object.

Override this method to specify a different equality relation on a class.

So whatever class it is you have there, I suggest you override the == operator, to make sure that two different instances of the same data still match. Otherwise you will see what you see now: only actual identical instances match.

Upvotes: 1

Related Questions