IdentifiantMot de passe
Loading...
Mot de passe oublié ?Je m'inscris ! (gratuit)
Navigation

Inscrivez-vous gratuitement
pour pouvoir participer, suivre les réponses en temps réel, voter pour les messages, poser vos propres questions et recevoir la newsletter

Android Discussion :

Authentification Google dans Flutter


Sujet :

Android

Vue hybride

Message précédent Message précédent   Message suivant Message suivant
  1. #1
    Membre très actif

    Homme Profil pro
    Hobbyiste
    Inscrit en
    Juillet 2018
    Messages
    129
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : Belgique

    Informations professionnelles :
    Activité : Hobbyiste

    Informations forums :
    Inscription : Juillet 2018
    Messages : 129
    Billets dans le blog
    1
    Par défaut Authentification Google dans Flutter
    Bonjour,

    J'utilise Flutter dernière version stable.
    voici:
    J'ai demandé à Gemini de m'écrire une classe pour authentification Firebase avec fournisseur Google la voici:
    Code : Sélectionner tout - Visualiser dans une fenêtre à part
    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    32
    33
    34
    35
    36
    37
    38
    39
    40
    41
    42
    43
    44
    45
    46
    47
    48
    49
    50
    51
    52
    53
    54
    55
    56
    57
    58
    59
    60
    61
    62
    63
    64
    65
    66
    67
    68
    69
    70
    71
    72
    73
    74
    75
    76
    77
    78
    79
    80
    81
    82
    83
    84
    85
    86
    87
    88
    89
    90
    91
    92
    93
    94
    95
    96
    97
    98
    99
    100
    101
    102
    103
    104
    105
    106
    107
    108
    109
    110
    111
    112
    113
    114
    115
    116
     
    import 'package:firebase_auth/firebase_auth.dart';
    import 'package:flutter/material.dart';
    import 'package:google_sign_in/google_sign_in.dart';
     
    /// A screen that provides a button to trigger Google Sign-In and handles the
    /// entire authentication flow with Firebase.
    class SignInDemo extends StatefulWidget {
      const SignInDemo({super.key});
     
      @override
      State<SignInDemo> createState() => _SignInDemoState();
    }
     
    class _SignInDemoState extends State<SignInDemo> {
      // A single, reusable instance of the GoogleSignIn client.
      final GoogleSignIn _googleSignIn = GoogleSignIn();
     
      // State to manage the loading indicator on the button.
      bool _isSigningIn = false;
     
      /// Performs the entire Google Sign-In flow and authenticates with Firebase.
      Future<void> _signInWithGoogle() async {
        // Prevent multiple sign-in attempts.
        if (_isSigningIn) return;
     
        setState(() {
          _isSigningIn = true;
        });
     
        try {
          // 1. Initiate the Google Sign-In flow.
          final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
     
          // If the user canceled the process, stop here.
          if (googleUser == null) {
            if (mounted) {
              ScaffoldMessenger.of(context).showSnackBar(
                const SnackBar(content: Text('Sign-in canceled by user.')),
              );
            }
            return; // Early exit
          }
     
          // 2. Obtain the authentication details from the Google user account.
          final GoogleSignInAuthentication googleAuth = await googleUser.authentication;
     
          // 3. Create a new Firebase credential using the Google tokens.
          final AuthCredential credential = GoogleAuthProvider.credential(
            accessToken: googleAuth.accessToken,
            idToken: googleAuth.idToken,
          );
     
          // 4. Sign in to Firebase with the new credential.
          // This action will be picked up by the StreamBuilder in AuthWrapper,
          // which will then navigate to the main application screen.
          await FirebaseAuth.instance.signInWithCredential(credential);
     
        } catch (e) {
          // Handle any errors that occur during the process.
          print('Error during Google sign-in: $e');
          if (mounted) {
            ScaffoldMessenger.of(context).showSnackBar(
              SnackBar(content: Text('Error: ${e.toString()}')),
            );
          }
        } finally {
          // Ensure the loading state is always reset, even if an error occurs.
          if (mounted) {
            setState(() {
              _isSigningIn = false;
            });
          }
        }
      }
     
      @override
      Widget build(BuildContext context) {
        return Scaffold(
          appBar: AppBar(
            title: const Text('Sign In'),
            elevation: 2,
          ),
          body: Center(
            child: Padding(
              padding: const EdgeInsets.all(24.0),
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  const Text(
                    'Welcome to Mesh Masks',
                    style: TextStyle(fontSize: 24, fontWeight: FontWeight.bold),
                  ),
                  const SizedBox(height: 16),
                  const Text(
                    'Please sign in with your Google account to continue.',
                    textAlign: TextAlign.center,
                  ),
                  const SizedBox(height: 48),
                  _isSigningIn
                      ? const CircularProgressIndicator()
                      : ElevatedButton.icon(
                          icon: const Icon(Icons.login), // Example icon
                          onPressed: _signInWithGoogle,
                          label: const Text('Sign In with Google'),
                          style: ElevatedButton.styleFrom(
                            minimumSize: const Size(double.infinity, 50), // Make button wider
                          ),
                        ),
                ],
              ),
            ),
          ),
        );
      }
    }
    La compilation donne 3 erreurs:


    > Task :app:compileFlutterBuildRelease
    lib/signin_screen.dart:16:38: Error: Couldn't find constructor 'GoogleSignIn'.
    final GoogleSignIn _googleSignIn = GoogleSignIn();
    ^^^^^^^^^^^^
    lib/signin_screen.dart:32:67: Error: The method 'signIn' isn't defined for the type 'GoogleSignIn'.
    - 'GoogleSignIn' is from 'package:google_sign_in/google_sign_in.dart' ('../../AppData/Local/Pub/Cache/hosted/pub.dev/google_sign_in-7.2.0/lib/google_sign_in.dart').
    Try correcting the name to the name of an existing method, or defining a method named 'signIn'.
    final GoogleSignInAccount? googleUser = await _googleSignIn.signIn();
    ^^^^^^
    lib/signin_screen.dart:49:33: Error: The getter 'accessToken' isn't defined for the type 'GoogleSignInAuthentication'.
    - 'GoogleSignInAuthentication' is from 'package:google_sign_in/src/token_types.dart' ('../../AppData/Local/Pub/Cache/hosted/pub.dev/google_sign_in-7.2.0/lib/src/token_types.dart').
    Try correcting the name to the name of an existing getter, or defining a getter or field named 'accessToken'.
    accessToken: googleAuth.accessToken,
    ^^^^^^^^^^^
    Target kernel_snapshot_program failed: Exception


    > Task :app:compileFlutterBuildRelease FAILED

  2. #2
    Expert confirmé
    Avatar de fred1599
    Homme Profil pro
    Lead Dev Python
    Inscrit en
    Juillet 2006
    Messages
    4 234
    Détails du profil
    Informations personnelles :
    Sexe : Homme
    Localisation : France, Meurthe et Moselle (Lorraine)

    Informations professionnelles :
    Activité : Lead Dev Python
    Secteur : Arts - Culture

    Informations forums :
    Inscription : Juillet 2006
    Messages : 4 234
    Par défaut
    Ces erreurs indiquent une incompatibilité entre le code écrit et la version de la dépendance google_sign_in que vous utilisez. Le code a été généré pour une ancienne version du package, et l'API a depuis introduit des "breaking changes"

    Il faut adapter votre code à cette version
    Celui qui trouve sans chercher est celui qui a longtemps cherché sans trouver.(Bachelard)
    La connaissance s'acquiert par l'expérience, tout le reste n'est que de l'information.(Einstein)

Discussions similaires

  1. Réponses: 0
    Dernier message: 20/08/2021, 09h54
  2. Integrer les résultats de google dans ma page web
    Par makaphrodite dans le forum Général Conception Web
    Réponses: 4
    Dernier message: 06/10/2007, 01h14
  3. integrer google dans ma page web
    Par makaphrodite dans le forum Balisage (X)HTML et validation W3C
    Réponses: 1
    Dernier message: 27/09/2007, 01h22
  4. authentification automatique dans IIS
    Par skywaukers dans le forum IIS
    Réponses: 1
    Dernier message: 26/07/2007, 22h41
  5. Comment insérer la recherche google dans son site ?
    Par freud dans le forum Services
    Réponses: 4
    Dernier message: 02/07/2005, 08h51

Partager

Partager
  • Envoyer la discussion sur Viadeo
  • Envoyer la discussion sur Twitter
  • Envoyer la discussion sur Google
  • Envoyer la discussion sur Facebook
  • Envoyer la discussion sur Digg
  • Envoyer la discussion sur Delicious
  • Envoyer la discussion sur MySpace
  • Envoyer la discussion sur Yahoo