随着 Getx 的大肆宣传,我选择在我的第一个项目中使用它,不幸的是,与其他人相比,关于 getx 的教程并不多。这是我的第一个构建,如何创建一个用户 ID 作为文档 ID,我遵循 MVC 模式,这是该构建的控制器。
这是我的代码。
import 'package:firebase_auth/firebase_auth.dart';
import 'package:get/get.dart';
import 'package:wlykmain/views/homepage.dart';
import 'package:wlykmain/views/login.dart';
class FirebaseController extends GetxController {
bool isHidden = true;
void toggleBetween() {
isHidden = !isHidden;
update();
}
FirebaseAuth _auth = FirebaseAuth.instance;
Rx<User> _firebaseUser = Rx<User>();
String get user => _firebaseUser.value?.email;
@override
// ignore: must_call_super
void onInit() {
_firebaseUser.bindStream(_auth.authStateChanges());
}
void signUp(
String firstname,
String lastname,
String email,
String password,
) async {
CollectionReference reference =
FirebaseFirestore.instance.collection("Users");
String uid = _auth.currentUser.uid;
reference.doc(uid).set({});
Map<String, dynamic> userdata = {
"First Name": firstname,
"Last Name": lastname,
"Email": email,
"uid": uid
};
await _auth
.createUserWithEmailAndPassword(email: email, password: password)
.then((value) {
reference.add(userdata).then((value) => (Get.offAll(LoginPage())));
}).catchError(
(onError) => Get.snackbar(
'Error creating account',
onError.message,
snackPosition: SnackPosition.TOP,
),
);
}
void login(String email, String password) async {
CollectionReference reference =
FirebaseFirestore.instance.collection("Users");
String uid = _auth.currentUser.uid;
reference.doc(uid).set({"uid": uid});
return await _auth
.signInWithEmailAndPassword(email: email, password: password)
// ignore: unnecessary_statements
.then((value) {
(Get.offAll(MyHome()));
}).catchError(
(onError) => Get.snackbar('Error while logging in', onError.message),
);
}
void signOut() async {
await _auth.signOut().then((value) => Get.offAll(LoginPage()));
}
}