Cannot access function parameters from async function - flutter

In the moment of registering, when I try to print the username which is a parameter of the function, it just won't print anything on the screen and I cannot understand why.
Future registerWithEmailAndPassword(String username, String email, String password) async {
try {
AuthResult result = await _auth.createUserWithEmailAndPassword(email: email, password: password);
FirebaseUser user = result.user;
// create a new document for the user with the uid
print(username);
await DatabaseService(uid: user.uid).updateUserData(username);
return _userFromFirebaseUser(user);
} catch (error) {
print(error.toString());
return null;
}
}
Edit: this is the function which calls the registerWithEmailAndPassword function:
onPressed: () async {
if (error.length > 0)
error = "";
if (_formKey.currentState.validate()) {
setState(() => loading = true);
dynamic result = await _auth.registerWithEmailAndPassword(username, email, password);
if (result == null){
if (this.mounted){
setState(() {
error = 'Please supply a valid email';
loading = false;
});}
}
}
}

Related

error : display a red line under this statement _userFromFirebaseUser(userCredential.user);

hi every one I'm trying making my app with flutter . it is contains a sign up page so I write the code and I'm retrieving an information from the firebase after I upload it .
the below code is the sign up code
UserModel? _userFromFirebaseUser(User userCredential) {
return userCredential != null
? UserModel(
id: userCredential.uid,
bannerImageUrl: '',
name: '',
email: '',
profileImageUrl: '')
: null;
}
Stream<UserModel?> get userCredential {
return auth
.authStateChanges()
.map((userCredential) => _userFromFirebaseUser(userCredential!));
}
Future SignUp(email, password) async {
var formdata = formstate.currentState;
if (formdata!.validate()) {
print("valid");
formdata.save();
try {
UserCredential userCredential =
(await auth.createUserWithEmailAndPassword(
email: myemail!, password: mypassword!));
FirebaseFirestore.instance
.collection('Users')
.doc(userCredential.user!.uid)
.set({'name': email, 'email': email});
_userFromFirebaseUser(userCredential.user);
return userCredential;
} on FirebaseAuthException catch (e) {
if (e.code == 'weak-password') {
Navigator.of(context).pop();
print('The password provided is too weak.');
} else if (e.code == 'email-already-in-use') {
Navigator.of(context).pop();
print('The account already exists for that email.');
}
} catch (e) {
print(e);
}
} else {}
}
and the red line appears on this line _userFromFirebaseUser(userCredential.user); as it is appears in the picture . please help me
userCredential.user is User? not User
change the method parameter
UserModel? _userFromFirebaseUser(User? userCredential) {
return ....
}

Strange error using Flutter app + Deno + MongoDB backend

I want to write a simple registration function and this is my code:
auth_screen.dart:
Future<void> _submit() async {
if (!_formKey.currentState!.validate()) {
// Invalid!
return;
}
_formKey.currentState!.save();
setState(() {
_isLoading = true;
});
try {
if (_authMode == AuthMode.Login) {
// Log user in
await Provider.of<Auth>(context, listen: false).login(
_authData['email'] as String,
_authData['password'] as String,
);
} else {
// Sign user up
await Provider.of<Auth>(context, listen: false).signup(
_authData['email'] as String,
_authData['password'] as String,
);
}
} on HttpException catch (error) {
var errorMessage = 'Authentication failed';
print("this is the auth data");
print(_authData);
if (error.toString().contains('EMAIL_EXISTS')) {
errorMessage = 'This email address is already in use.';
} else if (error.toString().contains('INVALID_EMAIL')) {
errorMessage = 'This is not a valid email address';
} else if (error.toString().contains('WEAK_PASSWORD')) {
errorMessage = 'This password is too weak.';
} else if (error.toString().contains('EMAIL_NOT_FOUND')) {
errorMessage = 'Could not find a user with that email.';
} else if (error.toString().contains('INVALID_PASSWORD')) {
errorMessage = 'Invalid password.';
}
_showErrorDialog(errorMessage);
} catch (error) {
var errorMessage = 'Could not authenticate you. Please try again later.' +
error.toString();
_showErrorDialog(errorMessage);
}
setState(() {
_isLoading = false;
});
}
auth.dart:
Future<void> signup(String email, String password) async {
return _authenticate(email, password, 'register');
}
Future<void> _authenticate(
String email, String password, String urlSegment) async {
final url = Uri.parse('http://10.0.2.2:8000/api/$urlSegment');
// final url = Uri.http('http://localhost:8000/api/', 'urlSegment');
try {
final response = await http.post(
url,
body: json.encode(
{
'email': email,
'password': password,
//'returnSecureToken': true,
},
),
);
final responseData = json.decode(response.body);
if (responseData['error'] != null) {
throw HttpException(responseData['error']['message']);
}
_token = responseData['idToken'];
_userId = responseData['localId'];
_expiryDate = DateTime.now().add(
Duration(
seconds: int.parse(
responseData['expiresIn'],
),
),
);
_autoLogout();
notifyListeners();
final prefs = await SharedPreferences.getInstance();
final userData = json.encode(
{
'token': _token,
'userId': _userId,
'expiryDate': _expiryDate!.toIso8601String(),
},
);
prefs.setString('userData', userData);
} catch (error) {
throw error;
}
}
This is the backend(Deno) part of the project:
auth_controller.ts:
async register(ctx: RouterContext) {
const { email, password } = await ctx.request.body().value;
let user = await User.findOne({ email });
if (user) {
ctx.response.status = 422;
ctx.response.body = { message: "Email is already exist" };
return;
}
const hashedPassword = hashSync(password);
user = new User({ email, password: hashedPassword });
await user.save();
ctx.response.status = 201;
ctx.response.body = {
id: user.id,
name: user.name,
email: user.email
};
}
And this is the user.ts class:
export default class User extends BaseModel {
public id: string = "";
public name: string = "";
public email: string = "";
public password: string = "";
constructor({ id = "", name = "", email = "", password = "" }) {
super();
this.id = id;
this.name = name;
this.email = email;
this.password = password;
}
static async findOne(params: object): Promise<User | null> {
const user = await userCollection.findOne(params);
if (!user) {
return null;
}
return new User(User.prepare(user));
}
async save() {
const _id = await userCollection.insertOne(this);
this.id = _id;
return this;
}
}
I get this error message when I want to test the application on Android emulator:
type 'Null' is not a subtype of type 'String'
When I try the backend server using Postman and send post request to http://0.0.0.0:8000/api/register address. I get correct response and it works, but I don't know why do I get Null response using the Flutter app?
I tried to print the variables in both front and backend side of the application and it seems they all are good and correct but I can not understand why do I get this error message?!
probably you got a null value in your map in this part since map return a null value when can't find a key, check if the Map value is not null
try {
if (_authMode == AuthMode.Login) {
// Log user in
await Provider.of<Auth>(context, listen: false).login(
_authData['email'] as String, // can return a null value
_authData['password'] as String, // can return a null value
);
} else {
// Sign user up
await Provider.of<Auth>(context, listen: false).signup(
_authData['email'] as String, // can return a null value
_authData['password'] as String, // can return a null value
);
}
}
Seems you're getting a null as a response value instead of a String.
EDIT:
Future<void> signup(String email, String password) async {
return _authenticate(email, password, 'register');
}
Check email and password are not null. And getting the correct values.
Actually the problem was from these two lines of code:
_token = responseData['idToken'];
_userId = responseData['localId'];
Because it wasn't passing these data in response from the backend side.

Flutter how to listen for email verification before user can sign in - firebase

My app allows the user to register and sends an email for verification. However i have a problem where the user can sign in with the new account whether the email is verified or not. I have looked and cannot find a solution to this bearing in mind i'm new to flutter
My Auth Code
Future<String> signIn(String email, String password) async {
AuthResult result = await _firebaseAuth.signInWithEmailAndPassword(
email: email, password: password);
FirebaseUser user = result.user;
if (user.isEmailVerified) {
return user.uid;
} else {
return null;
}
}
Future<String> signUp(String email, String password) async {
AuthResult result = await _firebaseAuth.createUserWithEmailAndPassword(
email: email, password: password);
FirebaseUser user = result.user;
try {
await user.sendEmailVerification();
return user.uid;
} catch (e) {
print("An error occurred while trying to send email verification");
print(e.message);
}
}
sign in method
try {
if (_isLoginForm) {
userId = await widget.auth.signIn(_email, _password);
print('Signed in: $userId');
} else {
userId = await widget.auth.signUp(_email, _password);
//widget.auth.sendEmailVerification();
_showVerifyEmailSentDialog();
print('Signed up user: $userId');
}
setState(() {
_isLoading = false;
});
if (userId.length > 0 && userId != null && _isLoginForm) {
widget.loginCallback();
}

Flutter, firebase. I want to show my registration form data other than the email and password and connect to a unique uid

Register Screen On Pressed method given, I believe there is a problem with calling Firebase user = result.user
onPressed: () async {
if(_formKey.currentState.validate()){
setState(() => loading = true);
dynamic result = await _auth.registerWithEmailAndPassword(email, password);
FirebaseUser user = result.user;
await DatabaseService(uid: user.uid).newUserInfo(
_nameC.text,
_cityC.text,
_contactnoC.toString()
);
if(result == null) {
setState(() {
error = 'Please supply a valid email';
loading = false;
});
}}},
// Database backend
class DatabaseService {
final String uid;
DatabaseService ({this.uid});
final CollectionReference userdata2 = Firestore.instance.collection('UserData');
Future newUserInfo(String name, String city, String contactno) async {
return await userdata2.document(uid).setData({
'name' : name,
'city' : city,
'contactno' : contactno
});
}}
// authentication backend
// register with email and password
Future registerWithEmailAndPassword(String email, String password) async {
try {
AuthResult result = await _auth.createUserWithEmailAndPassword(email: email, password: password);
FirebaseUser user = result.user;
DatabaseService(uid: user.uid);
return _userFromFirebaseUser(user);
} catch (error) {
print(error.toString());
return null;
} }
// user.dart
class User {
final String uid;
User({this.uid});
}

How can I resolve a problem with firebase registration?

I'm writing an application that have to register a user with firebase and than do the login. I wrote a function for the registration but the output give me this error:
PlatformException(error, Given String is empty or null, null)
This is the function:
Future registerWithEmailAndPassword(String email, String password) async {
try {
AuthResult result = await FirebaseAuth.instance.createUserWithEmailAndPassword(email: email, password: password);
FirebaseUser user = result.user;
Navigator.push(context, MaterialPageRoute(builder: (context) => Login()));
print(user);
return user;
} catch (e) {
print(e.toString());
return null;
}
}