To make my point clear I have created this small code..
it looks like I missing to understand concept of byref and byval here..
and what does actually Get.put works.
I have commented the lines what made me confused
GetxController
class UserController extends GetxController {
List<UserModel> _userlist = [];
UserModel? currentuser;
UserController() {
_userlist.add(UserModel(username: 'temp', password: 't123'));
}
List<UserModel> get getusers {
return _userlist;
}
}
this is main
void main()
{
final uc1=Get.put(UserController());
UserModel user1=UserModel(username: 'abc', password: 'a123');
uc1.currentuser=user1;
//showing print abc
print(uc1.currentuser!.username);
final uc2=Get.put(UserController());
UserModel user2=UserModel(username: 'xyz', password: 'x123');
uc2.currentuser=user2;
//showing printing result=xyz
print(uc2.currentuser!.username);
//showing printing result=xyz, instead of abc why?
print(uc1.currentuser!.username);
}
2
Answers
Because you are using the put method two time
if you want to update a single instance then follow the below code:
Get.put
only puts a new instance when there isn’t already one, (or the one that’s there is marked as dirty). You can see it by digging deeper into the code. Ctrl + clicking theput
method (in Android Studio at least) makes you able to see the implementation. The first step leads tothen doing it on
put
again leads toAnd digging into the
_insert
method gives:Here you can see that if it already exists and
isDirty
is true, or if it doesn’t exist yet, only then it inserts a new instance. Now I’m not entirely sure whenisDirty
is set, but I believe it happens when you change routes in your app. So the second time you callput
you are actually retrieving the one that is already put there before. Now if you want to have multiple instances you can useGet.create(() => UserController());
followed byGet.find
instead. Like: