使用 firebase 实现用户身份验证功能后,Flutter 应用程序重定向到空白 UI

问题描述 投票:0回答:1

我正在开发适用于 Android 的 Flutter 应用程序,在使用 Firebase 实现用户身份验证功能后遇到了应用程序导航行为的问题。我按照 WS Cube YouTube 频道的教程将 Firebase 身份验证集成到我的应用程序中。

1-我严格按照教程进行操作,确保将 Firebase 正确集成到我的 Flutter 应用程序中。

这是我在项目中使用的文件。

## pubsyml
name: firebase
description: "A new Flutter project."
publish_to: 'none'
version: 1.0.0+1

environment:
  sdk: '>=3.2.4 <4.0.0'

dependencies:
  flutter:
    sdk: flutter
  cupertino_icons: ^1.0.2
  firebase_core: ^2.27.0
  firebase_auth: ^4.17.8

dev_dependencies:
  flutter_test:
    sdk: flutter
  flutter_lints: ^3.0.2

flutter:
  uses-material-design: true

我的主要 dart 代码

import 'package:firebase/checkuser.dart';
import 'package:firebase/login.dart';
import 'package:firebase_core/firebase_core.dart';
import 'package:flutter/material.dart';

void main()async{
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp(
      options: FirebaseOptions(apiKey: "AIzaSyDQZxWx776Vhl7Hw4VG5RhaSPX13v6ygRk",
          appId: "1:1049018787351:android:309401ce75103c0f171e52",
          messagingSenderId: "1049018787351",
          projectId: "harsh-c8ebd")
  );
  runApp(const MyApp());
}


class MyApp extends StatelessWidget {
  const MyApp({super.key});
  @override
  Widget build(BuildContext context) {
    return MaterialApp(
      title: 'Flutter Demo',
      home: CheckUser(),
    );
  }
}

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Home Screen'),
      ),
      body: Text('hello'),
    );
  }
}

代码中的登录屏幕文件

import 'package:firebase/helper.dart';
import 'package:firebase/main.dart';
import 'package:firebase/signuppage.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

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

  @override
  State<Loginpage> createState() => _LoginpageState();
}

class _LoginpageState extends State<Loginpage> {
  TextEditingController emailcontroller = TextEditingController();
  TextEditingController passwordcontroller = TextEditingController();

   login(String email, String password) async {
    if (email == "" && password == "") {
      return Helper.CustomAlertBox(context, "Enter required fields");
    } else {
      try {
        UserCredential userCredential = await FirebaseAuth.instance
            .signInWithEmailAndPassword(email: email, password: password);
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => SignUpPage()),
        );
      } on FirebaseAuthException catch (ex) {
        return Helper.CustomAlertBox(context, ex.code.toString());
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Login page"),
        centerTitle: true,
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Helper.CustomTextField(emailcontroller, "Email", Icons.mail, false),
          Helper.CustomTextField(
              passwordcontroller, "Password", Icons.password, true),
          SizedBox(height: 30),
          Helper.CustomButton(
                () {
              login(emailcontroller.text.toString(),
                  passwordcontroller.text.toString());
            },
            "Login",
          ),
          SizedBox(height: 20),
          Row(
            mainAxisAlignment: MainAxisAlignment.center,
            children: [
              Text("Don't have an account?"),
              TextButton(
                onPressed: () {
                  Navigator.push(context,
                      MaterialPageRoute(builder: (context) => SignUpPage()));
                },
                child: Text(
                  "Sign up",
                  style: TextStyle(fontSize: 20),
                ),
              )
            ],
          )
        ],
      ),
    );
  }
}

注册屏幕代码

import 'package:firebase/helper.dart';
import 'package:firebase/main.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';

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

  @override
  State<SignUpPage> createState() => _SignUpPageState();
}

class _SignUpPageState extends State<SignUpPage> {
  TextEditingController emailcontroller = TextEditingController();
  TextEditingController passwordcontroller = TextEditingController();

   signUp(String email, String password) async {
    if (email == "" && password == "") {
      Helper.CustomAlertBox(context, "Enter required fields");
    } else {
      try {
        UserCredential userCredential = await FirebaseAuth.instance
            .createUserWithEmailAndPassword(email: email, password: password);
        Navigator.push(
          context,
          MaterialPageRoute(builder: (context) => HomeScreen()),
        );
      } on FirebaseAuthException catch (ex) {
        return Helper.CustomAlertBox(context, ex.code.toString());
      }
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text("Sign Up page"),
        centerTitle: true,
      ),
      body: Column(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Helper.CustomTextField(emailcontroller, "Email", Icons.mail, false),
          Helper.CustomTextField(passwordcontroller, "Password", Icons.password, true),
          SizedBox(height: 20),
          Helper.CustomButton(
                () {
              signUp(emailcontroller.text.toString(), passwordcontroller.text.toString());
            },
            "Sign Up",
          ),
        ],
      ),
    );
  }
}

帮助文件代码我在代码中用作帮助程序。

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

class Helper {
  static  CustomTextField(TextEditingController controller, String text, IconData iconData, bool tohide) {
    return Padding(
      padding: const EdgeInsets.symmetric(horizontal: 25, vertical: 40),
      child: TextField(
        controller: controller,
        obscureText: tohide,
        decoration: InputDecoration(
          hintText: text,
          suffixIcon: Icon(iconData),
          border: OutlineInputBorder(
            borderRadius: BorderRadius.circular(25),
          ),
        ),
      ),
    );
  }

  static  CustomButton(VoidCallback voidCallback, String text) {
    return SizedBox(
      height: 50,
      width: 300,
      child: ElevatedButton(
        onPressed: voidCallback,
        style: ElevatedButton.styleFrom(
          shape: RoundedRectangleBorder(
            borderRadius: BorderRadius.circular(25),
          ),
        ),
        child: Text(
          text,
          style: TextStyle(
            color: Colors.red,
            fontSize: 20,
          ),
        ),
      ),
    );
  }

  static Future<void> CustomAlertBox(BuildContext context, String text) {
    return showDialog(
      context: context,
      builder: (BuildContext context) {
        return AlertDialog(
          title: Text(text),
          actions: [
            TextButton(
              onPressed: () {
                Navigator.pop(context);
              },
              child: Text("OK"),
            ),
          ],
        );
      },
    );
  }
}
flutter firebase firebase-authentication
1个回答
0
投票

请将其从

main.dart
移至
homepage.dart

class HomeScreen extends StatefulWidget {
  @override
  _HomeScreenState createState() => _HomeScreenState();
}

class _HomeScreenState extends State<HomeScreen> {
  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: Text('Home Screen'),
      ),
      body: Text('hello'),
    );
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.