context.watch<用户?>()总是返回null

发布于 2025-02-12 02:03:28 字数 24105 浏览 0 评论 0原文

当我尝试使用最终firebaseuser = context.watch< user?>()时,当我尝试热重新启动应用程序时,firebaseuser的值始终为无效。并且在应用程序(电子邮件验证的用户)中的后登录后,adminscreen未构建。我已经使用了StreamProvider。

main.dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:heath_matthews_physio/screens/LogoutScreen.dart';
import 'package:heath_matthews_physio/screens/excercise.dart';
import 'package:heath_matthews_physio/screens/programsMy.dart';
import 'package:heath_matthews_physio/screens/AdminScreen.dart';
import 'package:heath_matthews_physio/screens/excerciseScreen.dart';
import 'package:heath_matthews_physio/screens/information_screen.dart';
import 'package:heath_matthews_physio/screens/login.dart';
import 'package:heath_matthews_physio/screens/mainScreen2.dart';
import 'package:heath_matthews_physio/screens/main_screen.dart';
import 'package:heath_matthews_physio/screens/myPrograms.dart';
import 'package:heath_matthews_physio/screens/reg_name_and_dp.dart';
import 'package:heath_matthews_physio/screens/register.dart';
import 'package:heath_matthews_physio/screens/verificationPage.dart';
import 'package:heath_matthews_physio/screens/workout-page.dart';
import 'package:heath_matthews_physio/screens/workoutScreen.dart';
import 'package:heath_matthews_physio/services/firebase_auth_methods.dart';
import 'package:heath_matthews_physio/wrapper.dart';
import 'package:provider/provider.dart';

import 'firebase_options.dart';
import 'screens/splash_screen.dart';
import 'package:firebase_core/firebase_core.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  runApp(
    MaterialApp(
      home: MyApp(),
      debugShowCheckedModeBanner: false,
    ),
  );
}

final navigatorKey = GlobalKey<NavigatorState>();

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        Provider<FirebaseAuthMethods>(
          create: (_) => FirebaseAuthMethods(FirebaseAuth.instance),
        ),
        StreamProvider(
          create: (context) => context.read<FirebaseAuthMethods>().authState,
          initialData: Null,
        ),
      ],
      child: GetMaterialApp(
        navigatorKey: navigatorKey,
        debugShowCheckedModeBanner: false,
        initialRoute: '/',
        routes: {
          // When navigating to the "/" route, build the FirstScreen widget.
          '/': (context) => const Splash(),
          // When navigating to the "/second" route, build the SecondScreen widget.
          '/wrapper': (context) => wrapper(),
          '/mainScreen': (context) => const mainScreen(),
          '/mainScreen2': (context) => const mainScreen2(),
          '/loginScreen': (context) => const Login(),
          '/registerScreen': (context) => const Register(),
          '/informationScreen': (context) => const informationScreen(),
          '/mainScreen2': (context) => const mainScreen2(),
          '/reg_name_and_dp': (context) => reg_name_and_dp(),
          '/myPrograms': (context) => const myPrograms(),
          '/adminScreen': (context) => adminScreen(),
          '/program': (context) => program(),
          '/workout-page': (context) => workoutScreen(),
          // '/exerciseScreen':(context)=>excerciseScreen(),
          '/exercise': (context) => exercise(),
          '/workoutScreen': (context) => workoutScreen1(),
          '/logout': (context) => logoutScreen(),
          '/verification': (context) => verificationPage(),
        },
        theme: ThemeData(
          primarySwatch: Colors.blue,
          accentColor: Color(0xFF193669),
        ),
      ),
    );
  }
}

splash_screen.dart

import 'package:flutter/material.dart';
import 'package:heath_matthews_physio/DynamicSize/size.dart';

class Splash extends StatefulWidget {
  const Splash({Key? key}) : super(key: key);

  @override
  _SplashState createState() => _SplashState();
}

class _SplashState extends State<Splash> {
  @override
  void initState() {
    super.initState();
    _navigateTologin();
  }

  _navigateTologin() async {
    await Future.delayed(Duration(milliseconds: 1500), () {});
    // Navigator.pushReplacementNamed(context, '/mainScreen');
    Navigator.pushReplacementNamed(context, '/wrapper');
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
          gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [
            Color.fromARGB(178, 25, 54, 105),
            Colors.white,
            Color(0xFFEDC152)
          ])),
      child: Padding(
        padding: EdgeInsets.all(DynamicSize.Aaheight(78.0)),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Image.asset("images/HMP LOGO.png"),
          ],
        ),
      ),
    );
  }
}

wrapper.dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'screens/AdminScreen.dart';
import 'screens/main_screen.dart';

class wrapper extends StatelessWidget {
  const wrapper({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final firebaseUser = context.watch<User?>();

    print("User : ${firebaseUser}"); //This always print null

    if (firebaseUser != null) {
      return adminScreen();
    } else {
      return mainScreen();
    }
  }
}

firebase_auth_methods.dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:heath_matthews_physio/screens/register.dart';

class FirebaseAuthMethods {
  final FirebaseAuth _auth;
  FirebaseAuthMethods(this._auth);

  //State Management
  Stream<User?> get authState => _auth.idTokenChanges();

  //Email Sign Up Function
  Future<void> singUpWithEmail({
    required String email,
    required String password,
    required BuildContext context,
  }) async {
    try {
      await _auth.createUserWithEmailAndPassword(
          email: email, password: password);
      await sendVerification(context);
    } on FirebaseAuthException catch (e) {
      print(e.message);
    }
  }

  //Email LogIn Function
  Future<void> signInWithEmail(
      {required String email,
      required String password,
      required BuildContext context}) async {
    try {
      await _auth.signInWithEmailAndPassword(email: email, password: password);
      if (!_auth.currentUser!.emailVerified) {
        await sendVerification(context);
      }
    } on FirebaseAuthException catch (e) {
      print(e.message);
    }
  }

  //Send Email Verification
  Future<void> sendVerification(BuildContext context) async {
    try {
      _auth.currentUser!.sendEmailVerification();
      popUpVerificationMsg(context);
    } on FirebaseAuthException catch (e) {
      print(e.message);
    }
  }
}

登录

import 'package:flutter/material.dart';
// import 'package:dotted_line/dotted_line.dart';
import 'package:heath_matthews_physio/DynamicSize/size.dart';
import 'package:heath_matthews_physio/services/firebase_auth_methods.dart';
import 'package:provider/provider.dart';

class Login extends StatefulWidget {
  const Login({Key? key}) : super(key: key);

  @override
  State<Login> createState() => _LoginState();
}

class _LoginState extends State<Login> {
  final emailController = TextEditingController();
  final passwordController = TextEditingController();
  @override
  void dispose() {
    emailController.dispose();
    passwordController.dispose();
    super.dispose();
  }

  //To Control PassWord Visibiltiy
  late bool _visibility;

  Future popUpConfirm(BuildContext context) {
    return showDialog(
      context: context,
      builder: (BuildContext context) {
        return Dialog(
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(DynamicSize.Faheight(16))),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            mainAxisSize: MainAxisSize.min,
            children: [
              Padding(
                padding: EdgeInsets.only(
                    left: DynamicSize.Fawidth(31),
                    top: DynamicSize.Faheight(24),
                    right: DynamicSize.Fawidth(31)),
                child: Image.asset('images/EmailSent.png'),
              ),

              //Msg
              SizedBox(height: DynamicSize.Faheight(24)),
              Padding(
                padding: EdgeInsets.only(
                    left: DynamicSize.Fawidth(16),
                    right: DynamicSize.Fawidth(16),
                    bottom: DynamicSize.Faheight(32)),
                child: Text(
                  "You will receive an email with intructions on how to reset your password in  a few minutes.\n\nNote : Don't forget to check your spam mail box.\n\nThank you :)",
                  style: TextStyle(
                    fontFamily: 'DMSans',
                    fontSize: DynamicSize.Faheight(16),
                    fontWeight: FontWeight.w400,
                    letterSpacing: DynamicSize.Fawidth(0.5),
                    color: Color(0xFF193669),
                    fontStyle: FontStyle.normal,
                  ),
                ),
              )
            ],
          ),
        );
      },
    );
  }

  Future popUpDialog(BuildContext context) {
    return showDialog(
      context: context,
      builder: (BuildContext context) {
        return Dialog(
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(DynamicSize.Faheight(16))),
          child: SingleChildScrollView(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              mainAxisSize: MainAxisSize.min,
              children: [
                Padding(
                  padding: EdgeInsets.only(
                      left: DynamicSize.Fawidth(31),
                      top: DynamicSize.Faheight(16),
                      right: DynamicSize.Fawidth(31)),
                  child: Image.asset('images/Illustration-forgot-password.png'),
                ),

                //Forgot password Text
                SizedBox(height: DynamicSize.Faheight(24)),
                Padding(
                  padding: EdgeInsets.only(left: DynamicSize.Fawidth(24)),
                  child: Align(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      'Forgot your password?',
                      style: TextStyle(
                        fontStyle: FontStyle.normal,
                        color: Color(0xFF193669),
                        fontFamily: 'DMSans',
                        fontSize: DynamicSize.Faheight(16),
                        fontWeight: FontWeight.w500,
                        letterSpacing: DynamicSize.Fawidth(1),
                      ),
                    ),
                  ),
                ),

                //Email Text
                SizedBox(height: DynamicSize.Faheight(36)),
                Padding(
                  padding: EdgeInsets.only(left: DynamicSize.Fawidth(24)),
                  child: Align(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      'Email',
                      style: TextStyle(
                        fontStyle: FontStyle.normal,
                        color: Color(0xFF193669),
                        fontFamily: 'DMSans',
                        fontSize: DynamicSize.Faheight(12),
                        fontWeight: FontWeight.w700,
                        letterSpacing: DynamicSize.Fawidth(1),
                      ),
                    ),
                  ),
                ),

                //Email TextField
                SizedBox(height: DynamicSize.Faheight(9)),
                Padding(
                  padding:
                      EdgeInsets.symmetric(horizontal: DynamicSize.Fawidth(24)),
                  child: TextField(
                    decoration: InputDecoration(
                      hintText: 'Email address',
                      hintStyle: TextStyle(
                        color: Color(0xFF636363),
                      ),
                      focusedBorder: new UnderlineInputBorder(
                        borderSide: BorderSide(color: Color(0xFF193669)),
                      ),
                    ),
                    keyboardType: TextInputType.emailAddress,
                  ),
                ),

                //Button
                SizedBox(height: DynamicSize.Faheight(24)),
                Padding(
                  padding:
                      EdgeInsets.symmetric(horizontal: DynamicSize.Fawidth(24)),
                  child: SizedBox(
                    width: double.infinity,
                    height: DynamicSize.Faheight(39),
                    child: OutlinedButton(
                      onPressed: () {
                        Navigator.pop(context);
                        popUpConfirm(context);
                      },
                      style: OutlinedButton.styleFrom(
                        side: BorderSide(
                          color: Color(0xFF193669),
                        ),
                        backgroundColor: Color(0xFFF0F2F4),
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(
                                DynamicSize.Faheight(15))),
                      ),
                      child: Text(
                        'Send me reset password instructions',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontFamily: 'DMSans',
                          fontStyle: FontStyle.normal,
                          fontWeight: FontWeight.w500,
                          fontSize: DynamicSize.Faheight(11),
                          letterSpacing: DynamicSize.Fawidth(0.8),
                          color: Color(0xFF193669),
                        ),
                      ),
                    ),
                  ),
                ),
                SizedBox(height: DynamicSize.Faheight(30)),
              ],
            ),
          ),
        );
      },
    );
  }

  @override
  void initState() {
    super.initState();
    _visibility = false;
  }

  void LoginUser() {
    context.read<FirebaseAuthMethods>().signInWithEmail(
        email: emailController.text.trim(),
        password: passwordController.text.trim(),
        context: context);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          //Grettings
          SizedBox(height: DynamicSize.Faheight(150)),
          Container(
            child: Text(
              "Welcome Back",
              style: TextStyle(
                fontFamily: 'DMSams',
                fontSize: DynamicSize.Faheight(30),
                fontWeight: FontWeight.w700,
                color: Color(0xff193669),
                letterSpacing: DynamicSize.Fawidth(0.5),
              ),
            ),
          ),
          SizedBox(height: DynamicSize.Faheight(17)),
          Container(
            margin: EdgeInsets.symmetric(horizontal: DynamicSize.Fawidth(17)),
            child: Text(
              'Hey, nice seeing you again !! Please login/register to continue further',
              textAlign: TextAlign.center,
              style: TextStyle(
                fontFamily: 'DMSans',
                fontSize: DynamicSize.Faheight(14),
                fontWeight: FontWeight.w600,
                color: Color(0xff193669),
                letterSpacing: DynamicSize.Fawidth(0.5),
              ),
            ),
          ),

          //User Credentials
          SizedBox(height: DynamicSize.Faheight(60)),
          Container(
            padding: EdgeInsets.symmetric(horizontal: DynamicSize.Fawidth(19)),
            margin: EdgeInsets.symmetric(horizontal: DynamicSize.Fawidth(25)),
            alignment: Alignment.center,
            height: DynamicSize.Faheight(50),
            decoration: BoxDecoration(
              color: Color(0xFFF3F3F3),
              borderRadius: BorderRadius.circular(DynamicSize.Faheight(15)),
              boxShadow: [
                BoxShadow(
                  offset: Offset(0, DynamicSize.Faheight(2)),
                  color: Color.fromARGB(141, 0, 0, 0),
                  blurRadius: DynamicSize.Faheight(3),
                ),
                BoxShadow(
                  offset: Offset(DynamicSize.Fawidth(-2), 0),
                  color: Color(0xFFF3F3F3),
                  blurRadius: DynamicSize.Faheight(1),
                ),
                BoxShadow(
                  offset: Offset(DynamicSize.Fawidth(2), 0),
                  color: Color(0xFFF3F3F3),
                  blurRadius: DynamicSize.Faheight(1),
                ),
              ],
            ),
            child: TextField(
              controller: emailController,
              style: TextStyle(
                fontFamily: 'DMSams',
                fontSize: DynamicSize.Faheight(14),
                letterSpacing: DynamicSize.Fawidth(0),
              ),
              decoration: InputDecoration(
                hintText: "Email address",
                border: InputBorder.none,
              ),
              keyboardType: TextInputType.emailAddress,
            ),
          ),

          //Password field
          SizedBox(height: DynamicSize.Faheight(15)),
          Container(
            padding: EdgeInsets.only(
                left: DynamicSize.Fawidth(19), right: DynamicSize.Fawidth(8)),
            margin: EdgeInsets.symmetric(horizontal: DynamicSize.Fawidth(25)),
            alignment: Alignment.center,
            height: DynamicSize.Faheight(50),
            decoration: BoxDecoration(
              color: Color(0xFFF3F3F3),
              borderRadius: BorderRadius.circular(DynamicSize.Faheight(15)),
              boxShadow: [
                BoxShadow(
                  offset: Offset(0, DynamicSize.Faheight(2)),
                  color: Color.fromARGB(141, 0, 0, 0),
                  blurRadius: DynamicSize.Faheight(3),
                ),
                BoxShadow(
                  offset: Offset(DynamicSize.Fawidth(-2), 0),
                  color: Color(0xFFF3F3F3),
                  blurRadius: DynamicSize.Faheight(1),
                ),
                BoxShadow(
                  offset: Offset(DynamicSize.Fawidth(2), 0),
                  color: Color(0xFFF3F3F3),
                  blurRadius: DynamicSize.Faheight(1),
                ),
              ],
            ),
            child: TextField(
              controller: passwordController,
              textAlignVertical: TextAlignVertical.center,
              style: TextStyle(
                fontFamily: 'DMSams',
                fontSize: DynamicSize.Faheight(14),
                letterSpacing: DynamicSize.Fawidth(0),
              ),
              decoration: InputDecoration(
                hintText: "Password",
                border: InputBorder.none,
                suffixIcon: IconButton(
                  splashRadius: 1,
                  splashColor: Colors.transparent,
                  icon: Icon(
                      _visibility ? Icons.visibility_off : Icons.visibility),
                  color: Color(_visibility ? (0xFF193669) : (0xFF666161)),
                  onPressed: () => setState(() => _visibility = !_visibility),
                ),
              ),
              obscureText: !_visibility,
            ),
          ),

          //Forgot Password Button
          SizedBox(height: DynamicSize.Faheight(13)),
          Container(
            padding: EdgeInsets.only(right: DynamicSize.Fawidth(36)),
            alignment: Alignment.topRight,
            child: GestureDetector(
              onTap: () => popUpDialog(context),
              child: Text(
                "Forgot Password ?",
                style: TextStyle(
                  fontFamily: "DMSans",
                  fontSize: DynamicSize.Faheight(15),
                  color: Color(0xFF193669),
                ),
              ),
            ),
          ),

          //Sign In Button
          SizedBox(height: DynamicSize.Faheight(40)),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: DynamicSize.Fawidth(15)),
            child: SizedBox(
              width: double.infinity,
              height: DynamicSize.Faheight(50),
              child: TextButton(
                onPressed: LoginUser,
                // Navigator.pushNamedAndRemoveUntil(
                // context, '/adminScreen', (route) => false),

                style: TextButton.styleFrom(
                    backgroundColor: Color(0xFF193669),
                    shape: RoundedRectangleBorder(
                      borderRadius:
                          BorderRadius.circular(DynamicSize.Faheight(15)),
                    )
                    // padding: EdgeInsets.symmetric(horizontal: 1),
                    ),
                child: Text(
                  'SIGN IN',
                  style: TextStyle(
                    fontFamily: 'DMSans',
                    fontSize: DynamicSize.Faheight(15),
                    letterSpacing: DynamicSize.Fawidth(0.5),
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ),

          //Register Button
          SizedBox(height: DynamicSize.Faheight(16)),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: DynamicSize.Fawidth(15)),
            child: SizedBox(
              width: double.infinity,
              height: DynamicSize.Faheight(50),
              child: TextButton(
                onPressed: () =>
                    Navigator.pushNamed(context, '/registerScreen'),
                style: TextButton.styleFrom(
                    backgroundColor: Color(0xFF193669),
                    shape: RoundedRectangleBorder(
                      borderRadius:
                          BorderRadius.circular(DynamicSize.Faheight(15)),
                    )
                    // padding: EdgeInsets.symmetric(horizontal: 1),
                    ),
                child: Text(
                  'REGISTER',
                  style: TextStyle(
                    fontFamily: 'DMSans',
                    fontSize: DynamicSize.Faheight(15),
                    letterSpacing: DynamicSize.Fawidth(0.5),
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ),
          // Row(
          //   children: [
          //     Text("No Account?",style: GoogleFonts.dmSans(
          //       fontSize: 12.0,
          //       color: Color(0xFF2F3F70)
          //     ),),
          //     Text("Sign Up",style: TextStyle(
          //       fontSize:12.0,
          //       fontWeight: FontWeight.w500,
          //       decoration: TextDecoration.underline,
          //       fontFamily: 'dmSams'
          //     ),
          //     )
          //   ],
          // )
        ],
      ),
    );
  }
}

When I try to use final firebaseUser = context.watch<User?>(), the value of firebaseUser is always null when I try to hot restart the application. And the after login IN (Email verified User) to application, the adminScreen is not build. I have used StreamProvider.

Main.dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:heath_matthews_physio/screens/LogoutScreen.dart';
import 'package:heath_matthews_physio/screens/excercise.dart';
import 'package:heath_matthews_physio/screens/programsMy.dart';
import 'package:heath_matthews_physio/screens/AdminScreen.dart';
import 'package:heath_matthews_physio/screens/excerciseScreen.dart';
import 'package:heath_matthews_physio/screens/information_screen.dart';
import 'package:heath_matthews_physio/screens/login.dart';
import 'package:heath_matthews_physio/screens/mainScreen2.dart';
import 'package:heath_matthews_physio/screens/main_screen.dart';
import 'package:heath_matthews_physio/screens/myPrograms.dart';
import 'package:heath_matthews_physio/screens/reg_name_and_dp.dart';
import 'package:heath_matthews_physio/screens/register.dart';
import 'package:heath_matthews_physio/screens/verificationPage.dart';
import 'package:heath_matthews_physio/screens/workout-page.dart';
import 'package:heath_matthews_physio/screens/workoutScreen.dart';
import 'package:heath_matthews_physio/services/firebase_auth_methods.dart';
import 'package:heath_matthews_physio/wrapper.dart';
import 'package:provider/provider.dart';

import 'firebase_options.dart';
import 'screens/splash_screen.dart';
import 'package:firebase_core/firebase_core.dart';

Future main() async {
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
    options: DefaultFirebaseOptions.currentPlatform,
  );
  runApp(
    MaterialApp(
      home: MyApp(),
      debugShowCheckedModeBanner: false,
    ),
  );
}

final navigatorKey = GlobalKey<NavigatorState>();

class MyApp extends StatelessWidget {
  const MyApp({Key? key}) : super(key: key);

  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return MultiProvider(
      providers: [
        Provider<FirebaseAuthMethods>(
          create: (_) => FirebaseAuthMethods(FirebaseAuth.instance),
        ),
        StreamProvider(
          create: (context) => context.read<FirebaseAuthMethods>().authState,
          initialData: Null,
        ),
      ],
      child: GetMaterialApp(
        navigatorKey: navigatorKey,
        debugShowCheckedModeBanner: false,
        initialRoute: '/',
        routes: {
          // When navigating to the "/" route, build the FirstScreen widget.
          '/': (context) => const Splash(),
          // When navigating to the "/second" route, build the SecondScreen widget.
          '/wrapper': (context) => wrapper(),
          '/mainScreen': (context) => const mainScreen(),
          '/mainScreen2': (context) => const mainScreen2(),
          '/loginScreen': (context) => const Login(),
          '/registerScreen': (context) => const Register(),
          '/informationScreen': (context) => const informationScreen(),
          '/mainScreen2': (context) => const mainScreen2(),
          '/reg_name_and_dp': (context) => reg_name_and_dp(),
          '/myPrograms': (context) => const myPrograms(),
          '/adminScreen': (context) => adminScreen(),
          '/program': (context) => program(),
          '/workout-page': (context) => workoutScreen(),
          // '/exerciseScreen':(context)=>excerciseScreen(),
          '/exercise': (context) => exercise(),
          '/workoutScreen': (context) => workoutScreen1(),
          '/logout': (context) => logoutScreen(),
          '/verification': (context) => verificationPage(),
        },
        theme: ThemeData(
          primarySwatch: Colors.blue,
          accentColor: Color(0xFF193669),
        ),
      ),
    );
  }
}

splash_screen.dart

import 'package:flutter/material.dart';
import 'package:heath_matthews_physio/DynamicSize/size.dart';

class Splash extends StatefulWidget {
  const Splash({Key? key}) : super(key: key);

  @override
  _SplashState createState() => _SplashState();
}

class _SplashState extends State<Splash> {
  @override
  void initState() {
    super.initState();
    _navigateTologin();
  }

  _navigateTologin() async {
    await Future.delayed(Duration(milliseconds: 1500), () {});
    // Navigator.pushReplacementNamed(context, '/mainScreen');
    Navigator.pushReplacementNamed(context, '/wrapper');
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      decoration: const BoxDecoration(
          gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [
            Color.fromARGB(178, 25, 54, 105),
            Colors.white,
            Color(0xFFEDC152)
          ])),
      child: Padding(
        padding: EdgeInsets.all(DynamicSize.Aaheight(78.0)),
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          crossAxisAlignment: CrossAxisAlignment.center,
          children: [
            Image.asset("images/HMP LOGO.png"),
          ],
        ),
      ),
    );
  }
}

wrapper.dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import 'screens/AdminScreen.dart';
import 'screens/main_screen.dart';

class wrapper extends StatelessWidget {
  const wrapper({Key? key}) : super(key: key);

  @override
  Widget build(BuildContext context) {
    final firebaseUser = context.watch<User?>();

    print("User : ${firebaseUser}"); //This always print null

    if (firebaseUser != null) {
      return adminScreen();
    } else {
      return mainScreen();
    }
  }
}

firebase_auth_methods.dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/material.dart';
import 'package:heath_matthews_physio/screens/register.dart';

class FirebaseAuthMethods {
  final FirebaseAuth _auth;
  FirebaseAuthMethods(this._auth);

  //State Management
  Stream<User?> get authState => _auth.idTokenChanges();

  //Email Sign Up Function
  Future<void> singUpWithEmail({
    required String email,
    required String password,
    required BuildContext context,
  }) async {
    try {
      await _auth.createUserWithEmailAndPassword(
          email: email, password: password);
      await sendVerification(context);
    } on FirebaseAuthException catch (e) {
      print(e.message);
    }
  }

  //Email LogIn Function
  Future<void> signInWithEmail(
      {required String email,
      required String password,
      required BuildContext context}) async {
    try {
      await _auth.signInWithEmailAndPassword(email: email, password: password);
      if (!_auth.currentUser!.emailVerified) {
        await sendVerification(context);
      }
    } on FirebaseAuthException catch (e) {
      print(e.message);
    }
  }

  //Send Email Verification
  Future<void> sendVerification(BuildContext context) async {
    try {
      _auth.currentUser!.sendEmailVerification();
      popUpVerificationMsg(context);
    } on FirebaseAuthException catch (e) {
      print(e.message);
    }
  }
}

login.dart

import 'package:flutter/material.dart';
// import 'package:dotted_line/dotted_line.dart';
import 'package:heath_matthews_physio/DynamicSize/size.dart';
import 'package:heath_matthews_physio/services/firebase_auth_methods.dart';
import 'package:provider/provider.dart';

class Login extends StatefulWidget {
  const Login({Key? key}) : super(key: key);

  @override
  State<Login> createState() => _LoginState();
}

class _LoginState extends State<Login> {
  final emailController = TextEditingController();
  final passwordController = TextEditingController();
  @override
  void dispose() {
    emailController.dispose();
    passwordController.dispose();
    super.dispose();
  }

  //To Control PassWord Visibiltiy
  late bool _visibility;

  Future popUpConfirm(BuildContext context) {
    return showDialog(
      context: context,
      builder: (BuildContext context) {
        return Dialog(
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(DynamicSize.Faheight(16))),
          child: Column(
            mainAxisAlignment: MainAxisAlignment.center,
            mainAxisSize: MainAxisSize.min,
            children: [
              Padding(
                padding: EdgeInsets.only(
                    left: DynamicSize.Fawidth(31),
                    top: DynamicSize.Faheight(24),
                    right: DynamicSize.Fawidth(31)),
                child: Image.asset('images/EmailSent.png'),
              ),

              //Msg
              SizedBox(height: DynamicSize.Faheight(24)),
              Padding(
                padding: EdgeInsets.only(
                    left: DynamicSize.Fawidth(16),
                    right: DynamicSize.Fawidth(16),
                    bottom: DynamicSize.Faheight(32)),
                child: Text(
                  "You will receive an email with intructions on how to reset your password in  a few minutes.\n\nNote : Don't forget to check your spam mail box.\n\nThank you :)",
                  style: TextStyle(
                    fontFamily: 'DMSans',
                    fontSize: DynamicSize.Faheight(16),
                    fontWeight: FontWeight.w400,
                    letterSpacing: DynamicSize.Fawidth(0.5),
                    color: Color(0xFF193669),
                    fontStyle: FontStyle.normal,
                  ),
                ),
              )
            ],
          ),
        );
      },
    );
  }

  Future popUpDialog(BuildContext context) {
    return showDialog(
      context: context,
      builder: (BuildContext context) {
        return Dialog(
          shape: RoundedRectangleBorder(
              borderRadius: BorderRadius.circular(DynamicSize.Faheight(16))),
          child: SingleChildScrollView(
            child: Column(
              mainAxisAlignment: MainAxisAlignment.center,
              mainAxisSize: MainAxisSize.min,
              children: [
                Padding(
                  padding: EdgeInsets.only(
                      left: DynamicSize.Fawidth(31),
                      top: DynamicSize.Faheight(16),
                      right: DynamicSize.Fawidth(31)),
                  child: Image.asset('images/Illustration-forgot-password.png'),
                ),

                //Forgot password Text
                SizedBox(height: DynamicSize.Faheight(24)),
                Padding(
                  padding: EdgeInsets.only(left: DynamicSize.Fawidth(24)),
                  child: Align(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      'Forgot your password?',
                      style: TextStyle(
                        fontStyle: FontStyle.normal,
                        color: Color(0xFF193669),
                        fontFamily: 'DMSans',
                        fontSize: DynamicSize.Faheight(16),
                        fontWeight: FontWeight.w500,
                        letterSpacing: DynamicSize.Fawidth(1),
                      ),
                    ),
                  ),
                ),

                //Email Text
                SizedBox(height: DynamicSize.Faheight(36)),
                Padding(
                  padding: EdgeInsets.only(left: DynamicSize.Fawidth(24)),
                  child: Align(
                    alignment: Alignment.centerLeft,
                    child: Text(
                      'Email',
                      style: TextStyle(
                        fontStyle: FontStyle.normal,
                        color: Color(0xFF193669),
                        fontFamily: 'DMSans',
                        fontSize: DynamicSize.Faheight(12),
                        fontWeight: FontWeight.w700,
                        letterSpacing: DynamicSize.Fawidth(1),
                      ),
                    ),
                  ),
                ),

                //Email TextField
                SizedBox(height: DynamicSize.Faheight(9)),
                Padding(
                  padding:
                      EdgeInsets.symmetric(horizontal: DynamicSize.Fawidth(24)),
                  child: TextField(
                    decoration: InputDecoration(
                      hintText: 'Email address',
                      hintStyle: TextStyle(
                        color: Color(0xFF636363),
                      ),
                      focusedBorder: new UnderlineInputBorder(
                        borderSide: BorderSide(color: Color(0xFF193669)),
                      ),
                    ),
                    keyboardType: TextInputType.emailAddress,
                  ),
                ),

                //Button
                SizedBox(height: DynamicSize.Faheight(24)),
                Padding(
                  padding:
                      EdgeInsets.symmetric(horizontal: DynamicSize.Fawidth(24)),
                  child: SizedBox(
                    width: double.infinity,
                    height: DynamicSize.Faheight(39),
                    child: OutlinedButton(
                      onPressed: () {
                        Navigator.pop(context);
                        popUpConfirm(context);
                      },
                      style: OutlinedButton.styleFrom(
                        side: BorderSide(
                          color: Color(0xFF193669),
                        ),
                        backgroundColor: Color(0xFFF0F2F4),
                        shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(
                                DynamicSize.Faheight(15))),
                      ),
                      child: Text(
                        'Send me reset password instructions',
                        textAlign: TextAlign.center,
                        style: TextStyle(
                          fontFamily: 'DMSans',
                          fontStyle: FontStyle.normal,
                          fontWeight: FontWeight.w500,
                          fontSize: DynamicSize.Faheight(11),
                          letterSpacing: DynamicSize.Fawidth(0.8),
                          color: Color(0xFF193669),
                        ),
                      ),
                    ),
                  ),
                ),
                SizedBox(height: DynamicSize.Faheight(30)),
              ],
            ),
          ),
        );
      },
    );
  }

  @override
  void initState() {
    super.initState();
    _visibility = false;
  }

  void LoginUser() {
    context.read<FirebaseAuthMethods>().signInWithEmail(
        email: emailController.text.trim(),
        password: passwordController.text.trim(),
        context: context);
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      resizeToAvoidBottomInset: false,
      body: Column(
        crossAxisAlignment: CrossAxisAlignment.center,
        children: [
          //Grettings
          SizedBox(height: DynamicSize.Faheight(150)),
          Container(
            child: Text(
              "Welcome Back",
              style: TextStyle(
                fontFamily: 'DMSams',
                fontSize: DynamicSize.Faheight(30),
                fontWeight: FontWeight.w700,
                color: Color(0xff193669),
                letterSpacing: DynamicSize.Fawidth(0.5),
              ),
            ),
          ),
          SizedBox(height: DynamicSize.Faheight(17)),
          Container(
            margin: EdgeInsets.symmetric(horizontal: DynamicSize.Fawidth(17)),
            child: Text(
              'Hey, nice seeing you again !! Please login/register to continue further',
              textAlign: TextAlign.center,
              style: TextStyle(
                fontFamily: 'DMSans',
                fontSize: DynamicSize.Faheight(14),
                fontWeight: FontWeight.w600,
                color: Color(0xff193669),
                letterSpacing: DynamicSize.Fawidth(0.5),
              ),
            ),
          ),

          //User Credentials
          SizedBox(height: DynamicSize.Faheight(60)),
          Container(
            padding: EdgeInsets.symmetric(horizontal: DynamicSize.Fawidth(19)),
            margin: EdgeInsets.symmetric(horizontal: DynamicSize.Fawidth(25)),
            alignment: Alignment.center,
            height: DynamicSize.Faheight(50),
            decoration: BoxDecoration(
              color: Color(0xFFF3F3F3),
              borderRadius: BorderRadius.circular(DynamicSize.Faheight(15)),
              boxShadow: [
                BoxShadow(
                  offset: Offset(0, DynamicSize.Faheight(2)),
                  color: Color.fromARGB(141, 0, 0, 0),
                  blurRadius: DynamicSize.Faheight(3),
                ),
                BoxShadow(
                  offset: Offset(DynamicSize.Fawidth(-2), 0),
                  color: Color(0xFFF3F3F3),
                  blurRadius: DynamicSize.Faheight(1),
                ),
                BoxShadow(
                  offset: Offset(DynamicSize.Fawidth(2), 0),
                  color: Color(0xFFF3F3F3),
                  blurRadius: DynamicSize.Faheight(1),
                ),
              ],
            ),
            child: TextField(
              controller: emailController,
              style: TextStyle(
                fontFamily: 'DMSams',
                fontSize: DynamicSize.Faheight(14),
                letterSpacing: DynamicSize.Fawidth(0),
              ),
              decoration: InputDecoration(
                hintText: "Email address",
                border: InputBorder.none,
              ),
              keyboardType: TextInputType.emailAddress,
            ),
          ),

          //Password field
          SizedBox(height: DynamicSize.Faheight(15)),
          Container(
            padding: EdgeInsets.only(
                left: DynamicSize.Fawidth(19), right: DynamicSize.Fawidth(8)),
            margin: EdgeInsets.symmetric(horizontal: DynamicSize.Fawidth(25)),
            alignment: Alignment.center,
            height: DynamicSize.Faheight(50),
            decoration: BoxDecoration(
              color: Color(0xFFF3F3F3),
              borderRadius: BorderRadius.circular(DynamicSize.Faheight(15)),
              boxShadow: [
                BoxShadow(
                  offset: Offset(0, DynamicSize.Faheight(2)),
                  color: Color.fromARGB(141, 0, 0, 0),
                  blurRadius: DynamicSize.Faheight(3),
                ),
                BoxShadow(
                  offset: Offset(DynamicSize.Fawidth(-2), 0),
                  color: Color(0xFFF3F3F3),
                  blurRadius: DynamicSize.Faheight(1),
                ),
                BoxShadow(
                  offset: Offset(DynamicSize.Fawidth(2), 0),
                  color: Color(0xFFF3F3F3),
                  blurRadius: DynamicSize.Faheight(1),
                ),
              ],
            ),
            child: TextField(
              controller: passwordController,
              textAlignVertical: TextAlignVertical.center,
              style: TextStyle(
                fontFamily: 'DMSams',
                fontSize: DynamicSize.Faheight(14),
                letterSpacing: DynamicSize.Fawidth(0),
              ),
              decoration: InputDecoration(
                hintText: "Password",
                border: InputBorder.none,
                suffixIcon: IconButton(
                  splashRadius: 1,
                  splashColor: Colors.transparent,
                  icon: Icon(
                      _visibility ? Icons.visibility_off : Icons.visibility),
                  color: Color(_visibility ? (0xFF193669) : (0xFF666161)),
                  onPressed: () => setState(() => _visibility = !_visibility),
                ),
              ),
              obscureText: !_visibility,
            ),
          ),

          //Forgot Password Button
          SizedBox(height: DynamicSize.Faheight(13)),
          Container(
            padding: EdgeInsets.only(right: DynamicSize.Fawidth(36)),
            alignment: Alignment.topRight,
            child: GestureDetector(
              onTap: () => popUpDialog(context),
              child: Text(
                "Forgot Password ?",
                style: TextStyle(
                  fontFamily: "DMSans",
                  fontSize: DynamicSize.Faheight(15),
                  color: Color(0xFF193669),
                ),
              ),
            ),
          ),

          //Sign In Button
          SizedBox(height: DynamicSize.Faheight(40)),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: DynamicSize.Fawidth(15)),
            child: SizedBox(
              width: double.infinity,
              height: DynamicSize.Faheight(50),
              child: TextButton(
                onPressed: LoginUser,
                // Navigator.pushNamedAndRemoveUntil(
                // context, '/adminScreen', (route) => false),

                style: TextButton.styleFrom(
                    backgroundColor: Color(0xFF193669),
                    shape: RoundedRectangleBorder(
                      borderRadius:
                          BorderRadius.circular(DynamicSize.Faheight(15)),
                    )
                    // padding: EdgeInsets.symmetric(horizontal: 1),
                    ),
                child: Text(
                  'SIGN IN',
                  style: TextStyle(
                    fontFamily: 'DMSans',
                    fontSize: DynamicSize.Faheight(15),
                    letterSpacing: DynamicSize.Fawidth(0.5),
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ),

          //Register Button
          SizedBox(height: DynamicSize.Faheight(16)),
          Padding(
            padding: EdgeInsets.symmetric(horizontal: DynamicSize.Fawidth(15)),
            child: SizedBox(
              width: double.infinity,
              height: DynamicSize.Faheight(50),
              child: TextButton(
                onPressed: () =>
                    Navigator.pushNamed(context, '/registerScreen'),
                style: TextButton.styleFrom(
                    backgroundColor: Color(0xFF193669),
                    shape: RoundedRectangleBorder(
                      borderRadius:
                          BorderRadius.circular(DynamicSize.Faheight(15)),
                    )
                    // padding: EdgeInsets.symmetric(horizontal: 1),
                    ),
                child: Text(
                  'REGISTER',
                  style: TextStyle(
                    fontFamily: 'DMSans',
                    fontSize: DynamicSize.Faheight(15),
                    letterSpacing: DynamicSize.Fawidth(0.5),
                    color: Colors.white,
                  ),
                ),
              ),
            ),
          ),
          // Row(
          //   children: [
          //     Text("No Account?",style: GoogleFonts.dmSans(
          //       fontSize: 12.0,
          //       color: Color(0xFF2F3F70)
          //     ),),
          //     Text("Sign Up",style: TextStyle(
          //       fontSize:12.0,
          //       fontWeight: FontWeight.w500,
          //       decoration: TextDecoration.underline,
          //       fontFamily: 'dmSams'
          //     ),
          //     )
          //   ],
          // )
        ],
      ),
    );
  }
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文