Authprovider mit dem Changenotifier
Code: Select all
class AuthProvider extends ChangeNotifier {
bool _isAuthenticated = false;
SharedPreferences _prefs;
GoogleSignIn _googleSignIn = GoogleSignIn(scopes: ['email']);
AuthProvider(this._prefs) {
_isAuthenticated = _prefs.getBool('isAuthenticated') ?? false;
}
bool get isAuthenticated => _isAuthenticated;
Future login() async {
try {
final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
if (googleUser?.email != null) {
_isAuthenticated = true;
_prefs.setBool('isAuthenticated', true);
notifyListeners();
}
} catch (error) {
print('Error signing in with Google: $error');
}
}
Future logout() async {
await _googleSignIn.signOut();
_isAuthenticated = false;
_prefs.setBool('isAuthenticated', false);
notifyListeners();
}
}
class AuthenticationWrapper extends StatelessWidget {
@override
Widget build(BuildContext context) {
final authProvider = Provider.of(context);
return authProvider.isAuthenticated ? Homepage() : WelcomePage();
}
}
Code: Select all
class _WelcomePageState extends State {
late AuthProvider authProvider;
@override
void initState() {
super.initState();
authProvider = Provider.of(context, listen: false);
}
Code: Select all
onTap: () async {
await authProvider.login();
},