dart 验证邮件后自动将用户发送到主页- Flutter-Firebase

ffvjumwh  于 12个月前  发布在  Flutter
关注(0)|答案(3)|浏览(219)

在我的应用程序中,用户注册后,他们会收到一封验证电子邮件。一旦他们验证了电子邮件并返回应用程序,我希望他们自动转到主页,而无需单击任何内容或重新启动应用程序。如何实现这一点?
使用authStateChanges

StreamBuilder(
      stream: FirebaseAuth.instance.authStateChanges(),

字符串
但没有用

oogrdqng

oogrdqng1#

在这里你可以试试这个:
1.Firebase Auth监听:在Flutter应用中设置一个身份验证状态监听器。该监听器应在“验证您的电子邮件”页面处于活动状态。
1.检查邮件验证状态:在监听器中,检查用户的邮件是否通过验证,可以通过检查Firebase用户对象的emailVerified属性来完成。
1.重定向到主页:如果emailVerified属性为true,则使用Flutter的导航器将用户重定向到主页。此重定向应自动进行,无需任何用户交互。
下面是执行此操作的代码片段:

FirebaseAuth.instance
  .authStateChanges()
  .listen((User user) {
    if (user != null && user.emailVerified) {
      // Redirect to the homepage
      Navigator.pushReplacementNamed(context, '/homepage');
    }
  });

字符串
它监听身份验证状态的变化。当用户的电子邮件通过验证时,它会自动导航到主页。我希望它能正常工作。😁

uqzxnwby

uqzxnwby2#

此代码将向用户的电子邮件地址发送验证电子邮件。电子邮件将包含用户必须单击以验证其电子邮件地址的链接。

Future<void> sendVerificationEmail() async {
 final user = FirebaseAuth.instance.currentUser!;
  await user.sendEmailVerification();
}

字符串
此代码将自动重定向到电子邮件验证后的网页.

Future<void> verifyEmail(BuildContext context) async {
    final user = await FirebaseAuth.instance.currentUser!;
    user.reload();
    if (user.emailVerified) {
      // Navigate to the homepage
      Navigator.pushReplacement(
        context,
        MaterialPageRoute(builder: (context) => HomePage()),
      );
    }
  }
}

jfgube3f

jfgube3f3#

下面是逻辑代码或更短的代码:

import 'package:firebase_auth/firebase_auth.dart';

final FirebaseAuth _auth = FirebaseAuth.instance;

return StreamBuilder(
  stream: _auth.authStateChanges(),
  builder: (context, snapshot) {
    if (snapshot.connectionState == ConnectionState.active) {
      User? user = snapshot.data as User?;
      if (user == null) {
        // User is not signed in
        return SignInScreen();
      } else {
        // Check if the user's email is verified
        if (user.emailVerified) {
          // User is signed in and email is verified, navigate to the homepage
          return HomeScreen();
        } else {
          // User is signed in but email is not verified, show verification screen
          return VerifyEmailScreen();
        }
      }
    }
    return CircularProgressIndicator();
  },
);

字符串
下面是完整的代码:

import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';

void main() {
  runApp(MyApp());
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      home: AuthenticationWrapper(),
    );
  }
}

class AuthenticationWrapper extends StatefulWidget {
  @override
  _AuthenticationWrapperState createState() => _AuthenticationWrapperState();
}

class _AuthenticationWrapperState extends State<AuthenticationWrapper> {
  final FirebaseAuth _auth = FirebaseAuth.instance;

  @override
  Widget build(BuildContext context) {
    return StreamBuilder(
      stream: _auth.authStateChanges(),
      builder: (context, snapshot) {
        if (snapshot.connectionState == ConnectionState.active) {
          User? user = snapshot.data as User?;
          if (user == null) {
            // User is not signed in
            return SignInScreen();
          } else {
            // Check if the user's email is verified
            if (user.emailVerified) {
              // User is signed in and email is verified, navigate to the homepage
              return HomeScreen();
            } else {
              // User is signed in but email is not verified, show verification screen
              return VerifyEmailScreen();
            }
          }
        }
        return CircularProgressIndicator();
      },
    );
  }
}

class SignInScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Sign In"),
      ),
      body: Center(
        child: ElevatedButton(
          onPressed: () async {
            // Perform sign-in logic here
          },
          child: Text("Sign In"),
        ),
      ),
    );
  }
}

class HomeScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Home"),
      ),
      body: Center(
        child: Text("Welcome to the homepage!"),
      ),
    );
  }
}

class VerifyEmailScreen extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Verify Email"),
      ),
      body: Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text("Please verify your email to access the homepage."),
            ElevatedButton(
              onPressed: () async {
                // Send email verification link
                User? user = FirebaseAuth.instance.currentUser;
                await user?.sendEmailVerification();
              },
              child: Text("Resend Verification Email"),
            ),
          ],
        ),
      ),
    );
  }
}

相关问题