I have a fixed List i.e fixGuestList that is being initialized in
init()
. On a button tap, a list of Guests appears. On tapping the guest, the selected guest is being added to the fixed list i.e fixGuestList. So basically I'm adding elements from one list to the fixed list.If the fixGuestList already contains the element present in the guestList. I want to pop up a snackBar() guest already added else add the element to fix list.
It is only working when the list is not been initialized. If I persist the list and on
init()
I assign the elements to the fixed list. And try to add duplicate guests the snackbar doesn't pop up it adds the duplicate guest to the list. For eg; I added guest 'A' from the guestList. And then I restarted the app and then again add the guest 'A' the guest 'A' is added even tho the fixedGuestList contains 'A' (I checked it in print statement 'A' exists) If I add 'A' and do not restart and try again try to add 'A' the snackbar pops up.Getx is being used as StateManagement and GetStorage is used for Persisit data. The values of both list are maps.
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'],
);
}
}