Created
June 4, 2019 13:07
-
-
Save guilhermecarvalhocarneiro/b85f23f912fde393caa73ab7f10f5510 to your computer and use it in GitHub Desktop.
Profile Flutter Page.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import 'dart:async'; | |
import 'package:firebase_auth/firebase_auth.dart'; | |
import 'package:flutter/material.dart'; | |
import 'package:google_sign_in/google_sign_in.dart'; | |
final FirebaseAuth _authUserFirebase = FirebaseAuth.instance; | |
final GoogleSignIn _googleSignIn = GoogleSignIn(); | |
GoogleSignInAccount _authUser = _googleSignIn.currentUser; | |
class Profile extends StatefulWidget { | |
@override | |
_ProfileState createState() => _ProfileState(); | |
} | |
class _ProfileState extends State<Profile> with SingleTickerProviderStateMixin { | |
AnimationController _controller; | |
final _scaffoldKey = GlobalKey<ScaffoldState>(); | |
@override | |
void initState() { | |
super.initState(); | |
_controller = AnimationController(vsync: this); | |
_userAuthentication(); | |
} | |
@override | |
void dispose() { | |
_controller.dispose(); | |
super.dispose(); | |
} | |
@override | |
Widget build(BuildContext context) { | |
return Scaffold( | |
appBar: AppBar( | |
title: Text("Perfil"), | |
centerTitle: true, | |
backgroundColor: Colors.green, | |
), | |
key: _scaffoldKey, | |
body: _createBody(context), | |
); | |
} | |
_message(String message, {bool error}) { | |
setState(() { | |
if (error == true) { | |
final snackBar = | |
SnackBar(content: Text(message), backgroundColor: Colors.red); | |
_scaffoldKey.currentState.showSnackBar(snackBar); | |
} else { | |
final snackBar = SnackBar( | |
content: Text(message), backgroundColor: Colors.lightBlueAccent); | |
_scaffoldKey.currentState.showSnackBar(snackBar); | |
} | |
}); | |
} | |
Widget _createBody(context) { | |
if (_authUser == null) { | |
return Center( | |
child: RaisedButton.icon( | |
icon: const Icon(Icons.account_circle), | |
label: const Text('Logar com o Google'), | |
onPressed: _userAuthentication, | |
color: Colors.white, | |
), | |
); | |
} else { | |
return Padding( | |
padding: const EdgeInsets.only(top:32), | |
child: Column( | |
crossAxisAlignment: CrossAxisAlignment.center, | |
mainAxisAlignment: MainAxisAlignment.center, | |
children: <Widget>[ | |
Center( | |
child: Container( | |
width: 190.0, | |
height: 190.0, | |
decoration: BoxDecoration( | |
shape: BoxShape.circle, | |
image: DecorationImage( | |
image: NetworkImage(_authUser.photoUrl), | |
fit: BoxFit.fill)), | |
), | |
), | |
Padding( | |
padding: const EdgeInsets.only(top: 16.0), | |
child: Text( | |
_authUser.displayName, | |
style: Theme.of(context).textTheme.subtitle, | |
), | |
), | |
Padding( | |
padding: const EdgeInsets.only(top: 8.0), | |
child: Text( | |
_authUser.email, | |
style: | |
Theme.of(context).textTheme.subhead.copyWith(fontSize: 18.0), | |
), | |
), | |
// O Spacer faz com que os itens abaixo dele sejam todos | |
// reposicionados na parte inferior da tela | |
Spacer(), | |
Padding( | |
padding: const EdgeInsets.only(bottom:12.0), | |
child: Center( | |
child: RaisedButton( | |
child: const Text('Sair do sistema'), | |
onPressed: () { | |
setState(() { | |
_authUserFirebase.signOut().then((item) { | |
_message('Efetuado Logout'); | |
}).catchError((error) { | |
_message(error, error: true); | |
}); | |
_googleSignIn.signOut().then((google) { | |
_message('Efetuado Logout'); | |
}).catchError((error) { | |
_message(error, error: true); | |
}); | |
}); | |
}, | |
), | |
), | |
) | |
], | |
), | |
); | |
} | |
} | |
Future<Null> _userAuthentication() async { | |
GoogleSignInAuthentication _credentials; | |
// Verificando se existe usuário logado | |
setState(() { | |
if (_authUser == null) { | |
// Invocando o método de login do Google de forma silenciosa | |
_googleSignIn.signInSilently().then((user) { | |
_authUser = user; | |
if (_authUser == null) { | |
_googleSignIn.signIn().then((user) { | |
// Tentado efetuar o login de forma não silenciosa | |
_authUser = user; | |
// Verificando se o usuário do Firebase é nulo | |
_authUserFirebase.currentUser().then((userFirebase) { | |
if (userFirebase == null) { | |
// Rercuperando as credencias da conta Google | |
_googleSignIn.currentUser.authentication.then((credentials) { | |
final _tokenID = _credentials.idToken; | |
final _tokenAccess = _credentials.accessToken; | |
// Tratando o usuário retornado pelo método de login acima | |
if (_authUser != null && userFirebase == null) { | |
// Realizando a autenticação do usuário no Firebase | |
final AuthCredential _authCredential = | |
GoogleAuthProvider.getCredential( | |
accessToken: _tokenAccess, idToken: _tokenID); | |
_authUserFirebase | |
.signInWithCredential(_authCredential) | |
.then((firebaseCredential) { | |
_message( | |
"Seja bem vindo ao Indikai ${_authUser.displayName}"); | |
// Chamando o método para salvar os dados do usuário no banco | |
// TODO Salvar no SharedPreferences | |
}).catchError(() { | |
_message("Ocorreu um error, favor tentar novamente.", | |
error: true); | |
}); | |
} else { | |
_message('Login não efetuado'); | |
} | |
}).catchError((error) { | |
_message(error, error: true); | |
}); | |
} | |
}).catchError((error) {}); | |
}).catchError((error) { | |
_message(error.toString(), error: true); | |
}); | |
} else { | |
// Verificando se o usuário do Firebase é nulo | |
_authUserFirebase.currentUser().then((userFirebase) { | |
if (userFirebase == null) { | |
// Rercuperando as credencias da conta Google | |
_googleSignIn.currentUser.authentication.then((credentials) { | |
final _tokenID = credentials.idToken; | |
final _tokenAccess = credentials.accessToken; | |
// Tratando o usuário retornado pelo método de login acima | |
if (_authUser != null && userFirebase == null) { | |
// Realizando a autenticação do usuário no Firebase | |
final AuthCredential _authCredential = | |
GoogleAuthProvider.getCredential( | |
accessToken: _tokenAccess, idToken: _tokenID); | |
_authUserFirebase | |
.signInWithCredential(_authCredential) | |
.then((firebaseCredential) { | |
_message( | |
"Seja bem vindo ao Indikai ${_authUser.displayName}"); | |
// Chamando o método para salvar os dados do usuário no banco | |
}).catchError(() { | |
_message("Ocorreu um error, favor tentar novamente.", | |
error: true); | |
}); | |
} else { | |
_message('Login não efetuado'); | |
} | |
}).catchError((error) { | |
_message(error, error: true); | |
}); | |
} | |
}).catchError((error) { | |
_message(error, error: true); | |
}); | |
} | |
}).catchError((error) { | |
_message(error, error: true); | |
}); | |
} | |
}); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment