I’ve tried asking this question to ChatGPT and CopilotBing, but I want to know more clearly from someone more experienced.
Case 1
If I have a controller class ‘HomeController’ like this:
class HomeController {
final currentUserId = AuthService.to.user!.uid;
}
and I have a method in that class named ‘createTask’, and I call the ‘createTask’ method from the UI code ‘home_view.dart’.
However, ‘createTask’ requires the ‘currentUserId’ data.
The question is, should I call ‘createTask like this in ‘home_view.dart’:
controller.createTask(controller.currentUserId)
or just like this:
controller.createTask()
and the ‘currentUserId’ parameter is obtained like this:
class HomeController {
final currentUserId = AuthService.to.user!.uid;
void createTask(){
print(currentUserId);
}
}
Case 2
I have a controller class ‘SearchUserController’ like this:
class SearchUserController extends GetxController {
final search = ''.obs;
final displayName = 'testing';
}
and I have a method in that class named ‘_searchUser’.
I call the method using ‘onInit’ from ‘SearchUserController’ and listen for changes every time the search variable changes using debounce.
The question is, is it better to call the ‘_searchUser’ method like this:
@override
void onInit() {
debounce(
search,
(receiverName) => _searchUser(displayName, receiverName),
);
super.onInit();
}
or just like this:
@override
void onInit() {
debounce(
search,
(_) => _searchUser(),
);
super.onInit();
}
and the ‘_searchUser’ method is like this:
void _searchUser() {
print(displayName);
print(search.value);
}
Case 3
I have a class ‘AuthService’ like this:
class AuthService extends GetxService {
late Rx<User?> _user;
User? get user => _user.value;
}
then I want to assign the ‘_user’ variable like this:
@override
void onInit() {
_user = Rx<User?>(FirebaseAuth.instance.currentUser);
_user.bindStream(FirebaseAuth.instance.userChanges());
super.onInit();
}
and then I want to check the ‘_user’ variable every time it changes using ‘ever’.
The question is, what is the best way to write the code in ‘onInit’?
Case 1: How to correctly retrieve a variable within a method if it already exists within the class itself.
Case 2 and 3: How to correctly use Workers in GetX.