Flutter和Firebase认证

avwztpqn  于 12个月前  发布在  Flutter
关注(0)|答案(2)|浏览(141)

我试图将我的flutter应用程序连接到firebase以保存用户数据并对他进行身份验证数据已在firestore中成功保存,但身份验证dosent工作depandncy是确定的,因为在onther页面中身份验证成功,我使用电子邮件passowrd身份验证最简单的一个
这是我的依赖项,我导入所有的pakage,我做everting作为firebase.flutter.dev告诉我这样做,这是我的代码,我删除UI的细节,我试图导入
Firebase核心Firebase授权云Firestore
我开始建立连接,这是代码
onPressed()我试图发送电子邮件和密码,在textfilde之前
addUser()是将详细信息存储到firestore的方法

void main() async{
  runApp(MyApp());
  WidgetsFlutterBinding.ensureInitialized();
  await Firebase.initializeApp();
}

class MyApp extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MaterialApp(home: HomePage(), routes: <String, WidgetBuilder>{
      '/AsDocter': (context) => AsDoctor(),
      '/AsPatient': (context) => AsPatient(),
      '/Login': (context) => Login()
    });
  }
}



class AsDoctor extends StatefulWidget {
  @override
  _AsDoctorState createState() => _AsDoctorState();
}

class _AsDoctorState extends State<AsDoctor> {
  String email = ''; // Initialize with an empty string
  String password = ''; // Initialize with an empty string
  String firstName = ''; // Create a variable for the First Name
  String lastName = ''; // Create a variable for the Last Name
  String id = ''; // Create a variable for the ID
  String phoneNumber = ''; // Create a variable for Phone Number
  String city = ''; // Create a variable for the City
  String gender = ''; // Create a variable for Gender
  String license = ''; // Create a variable for License
  String formattedDate = ''; // Initialize with an empty string

  DateTime?
  selectedDate; // Create a DateTime variable to store the selected date
  File? selectedFile; // Create a File variable to store the selected file

  // Function to show the date picker
  Future<void> _selectDate(BuildContext context) async {
    final DateTime picked = (await showDatePicker(
      context: context,
      initialDate: selectedDate ?? DateTime.now(),
      firstDate: DateTime(1900),
      lastDate: DateTime(2101),
    ))!;
    if (picked != null && picked != selectedDate)
      setState(() {
        selectedDate = picked;
      });
  }

  // Function to pick a file
  void _pickFile() async {
    FilePickerResult? result = await FilePicker.platform.pickFiles();
    if (result != null) {
      setState(() {
        selectedFile = File(result.files.single.path!);
      });
    }
  }
    CollectionReference Doctor = FirebaseFirestore.instance.collection('Doctors');

    // Create a map with the user data
    Future<void> addUser() {
      // Call the user's CollectionReference to add a new user
      return Doctor
          .add({
        'First Name': firstName,
        'Last Name': lastName,
        'ID': id,
        'Email': email,
        'Phone Number': phoneNumber,
        'City': city,
        'Gender': gender,
      })
          .then((value) => print("User Added"))
          .catchError((error) => print("Failed to add user: $error"));
    }

  @override
  Widget build(BuildContext context) {
    String formattedDate = selectedDate != null
        ? "${selectedDate!.year}-${selectedDate!.month.toString().padLeft(2, '0')}-${selectedDate!.day.toString().padLeft(2, '0')}"
        : "Date of Birth";

    return Scaffold(
      appBar: AppBar(
        title: Text('Doctor Page'),
      ),
      body: SingleChildScrollView(
        child: Container(
          width: 430,
          height: 1050,
          clipBehavior: Clip.antiAlias,
          decoration: BoxDecoration(color: Colors.white),
          child: Stack(
            children: [
              Positioned(
                left: -67,
                top: -35,
                child: Container(
                  width: 564,
                  height: 1150,
                  decoration: BoxDecoration(
                    image: DecorationImage(
                      image: AssetImage('img/background.png'),
                      fit: BoxFit.fill,
                    ),
                  ),
                ),
              ), // Background
              Positioned(
                left: 20,
                top: 118,
                child: Container(
                  width: 375,
                  height: 949,
                  decoration:
                  BoxDecoration(color: Colors.white.withOpacity(0.5)),
                ),
              ),
              Positioned(
                left: 163,
                top: 65,
                child: Container(
                  width: 108,
                  height: 107,
                  decoration: ShapeDecoration(
                    color: Color(0xFF0A8DD3),
                    shape: CircleBorder(),
                    shadows: [
                      BoxShadow(
                        color: Color(0x3F000000),
                        blurRadius: 4,
                        offset: Offset(0, 4),
                        spreadRadius: 0,
                      )
                    ],
                  ),
                ),
              ),
              // First Name TextBox
              Positioned(
                left: 72,
                top: 201,
                child: Container(
                  width: 250, // Adjust the width
                  child: TextFormField(
                    onChanged: (value) {
                      setState(() {
                        firstName = value;
                      });
                    },
                    decoration: InputDecoration(
                      hintText: 'First Name',
                      fillColor: Colors.white,
                      filled: true,
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(15.0),
                      ),
                    ),
                  ),
                ),
              ),
              // Last Name TextBox
              Positioned(
                left: 72,
                top: 276, // Adjust the top position
                child: Container(
                  width: 250, // Adjust the width
                  child: TextFormField(
                    onChanged: (value) {
                      setState(() {
                        lastName = value;
                      });
                    },
                    decoration: InputDecoration(
                      hintText: 'Last Name',
                      fillColor: Colors.white,
                      filled: true,
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(15.0),
                      ),
                    ),
                  ),
                ),
              ),
              // ID TextBox
              Positioned(
                left: 72,
                top: 351, // Adjust the top position
                child: Container(
                  width: 250, // Adjust the width
                  child: TextFormField(
                    onChanged: (value) {
                      setState(() {
                        id = value;
                      });
                    },
                    decoration: InputDecoration(
                      hintText: 'ID',
                      fillColor: Colors.white,
                      filled: true,
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(15.0),
                      ),
                    ),
                  ),
                ),
              ),
              // Email TextBox
              Positioned(
                left: 72,
                top: 426, // Adjust the top position
                child: Container(
                  width: 250, // Adjust the width
                  child: TextFormField(
                    onChanged: (value) {
                      setState(() {
                        email = value;
                      });
                    },
                    decoration: InputDecoration(
                      hintText: 'Email',
                      fillColor: Colors.white,
                      filled: true,
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(15.0),
                      ),
                    ),
                  ),
                ),
              ),
              // Phone Number TextBox
              Positioned(
                left: 72,
                top: 501, // Adjust the top position
                child: Container(
                  width: 250, // Adjust the width
                  child: TextFormField(
                    onChanged: (value) {
                      setState(() {
                        phoneNumber = value;
                      });
                    },
                    decoration: InputDecoration(
                      hintText: 'Phone Number',
                      fillColor: Colors.white,
                      filled: true,
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(15.0),
                      ),
                    ),
                  ),
                ),
              ),
              // City TextBox
              Positioned(
                left: 72,
                top: 576,
                // Adjust the top position
                child: Container(
                  width: 250, // Adjust the width
                  child: TextFormField(
                    onChanged: (value) {
                      setState(() {
                        city = value;
                      });
                    },
                    decoration: InputDecoration(
                      hintText: 'City',
                      fillColor: Colors.white,
                      filled: true,
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(15.0),
                      ),
                    ),
                  ),
                ),
              ),
              // Gender TextBox
              Positioned(
                left: 72,
                top: 651,
                // Adjust the top position
                child: Container(
                  width: 250, // Adjust the width
                  child: TextFormField(
                    onChanged: (value) {
                      setState(() {
                        gender = value;
                      });
                    },
                    decoration: InputDecoration(
                      hintText: 'Gender',
                      fillColor: Colors.white,
                      filled: true,
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(15.0),
                      ),
                    ),
                  ),
                ),
              ),
              // License TextBox
              Positioned(
                left: 72,
                top: 800,
                // Adjust the top position
                child: Container(
                  width: 250, // Adjust the width
                  child: Column(
                    crossAxisAlignment: CrossAxisAlignment.start,
                    children: [
                      Text(
                        'Import License:',
                        style: TextStyle(
                          fontSize: 18,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                      SizedBox(height: 10),
                      ElevatedButton(
                        onPressed: _pickFile, // Open file picker
                        style: ElevatedButton.styleFrom(
                          primary: Color(0xFF0A8DD3),
                          padding: EdgeInsets.symmetric(
                              vertical: 10, horizontal: 20),
                          shape: RoundedRectangleBorder(
                            borderRadius: BorderRadius.circular(10),
                          ),
                          shadowColor: Color(0x3F000000),
                          elevation: 4,
                        ),
                        child: Text(
                          selectedFile != null
                              ? 'File Selected'
                              : 'Select License File',
                          style: TextStyle(
                            color: Colors.white,
                            fontSize: 16,
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              // Password TextBox
              Positioned(
                left: 72,
                top: 726,
                // Adjust the top position
                child: Container(
                  width: 250, // Adjust the width
                  child: TextFormField(
                    obscureText: true, // For password fields
                    decoration: InputDecoration(
                      hintText: 'Password',
                      fillColor: Colors.white,
                      filled: true,
                      border: OutlineInputBorder(
                        borderRadius: BorderRadius.circular(15.0),
                      ),
                    ),
                  ),
                ),
              ),
              // Date of Birth TextBox
              Positioned(
                left: 72,
                top: 876, // Adjust the top position
                child: Container(
                  width: 250, // Adjust the width
                  child: Row(
                    children: [
                      Expanded(
                        child: Text(
                          'Date of Birth:',
                          style: TextStyle(
                            fontSize: 18,
                            fontWeight: FontWeight.bold,
                          ),
                        ),
                      ),
                      SizedBox(width: 10),
                      Expanded(
                        child: TextButton(
                          onPressed: () =>
                              _selectDate(context), // Show date picker
                          child: Text(
                            formattedDate, // Display selected date
                            style: TextStyle(
                              fontSize: 18,
                            ),
                          ),
                        ),
                      ),
                    ],
                  ),
                ),
              ),
              // Sign In Button
              Positioned(
                left: 90,
                top: 951, // Adjust the top position
                child: ElevatedButton(
                  onPressed: ()  async{
                    addUser();
                    try {
                      final credential = await FirebaseAuth.instance.createUserWithEmailAndPassword(
                        email: email,
                        password: password,
                      );
                      print('===================================done');
                    } on FirebaseAuthException catch (e) {
                      if (e.code == 'weak-password') {
                        print('The password provided is too weak.');
                      } else if (e.code == 'email-already-in-use') {
                        print('The account already exists for that email.');
                      }
                    } catch (e) {
                      print(e);
                    }
                  },
                  style: ElevatedButton.styleFrom(
                    backgroundColor: Color(0xFF0A8DD3),
                    padding: EdgeInsets.symmetric(vertical: 15, horizontal: 70),
                    shape: RoundedRectangleBorder(
                      borderRadius: BorderRadius.circular(10),
                    ),
                    shadowColor: Color(0x3F000000),
                    elevation: 4,
                  ),
                  child: Text(
                    'Sign in',
                    textAlign: TextAlign.center,
                    style: TextStyle(
                      color: Colors.white,
                      fontSize: 25,
                      fontFamily: 'Inter',
                      fontWeight: FontWeight.w900,
                      height: 0,
                    ),
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}
zed5wv10

zed5wv101#

看起来像是您在向Firestore添加用户数据后,试图使用Firebase身份验证(UserWithEmailAndPassword)创建用户。但是,您的代码中存在一些可能导致问题的问题。以下是一些建议,可帮助您进行故障排除并可能修复问题:
密码丢失:您正在使用Password UserWithEmailAndPassword中的密码变量,但未在代码中的任何位置设置密码变量。您应该捕获用户输入的密码,并在身份验证中使用它之前将其设置为密码变量。
异步代码:Firebase身份验证函数是异步的,等待它们是很重要的。请确保在调用验证UserWithEmailAndPassword时使用await,以确保在继续之前等待身份验证完成。
以下是代码的更新版本,其中包含以下注意事项:
//...(其他导入和代码)
class _AsDoctorState extends State { //.
//密码文本框定位(左:72,top:726,//调整顶部位置子项:容器(宽度:250,//调整子元素的宽度:TextFormField(obscureText:true,//对于密码字段onChanged:(value){ setState((){ password = value;//捕获密码输入});},装饰:InputDecoration(hintText:'Password',fillColor:颜色。白色,填充:true,border:OutlineInputBorder(borderRadius:BorderRadius.circular(15.0),),
//登录按钮已定位(左侧:90,top:951,//调整最高位置子项:抬起按钮(按下:()c { //捕获在addUser()中添加用户和登录之前输入的密码; try { final credential = await FirebaseAuth.instance . UserWithEmailAndPassword(电子邮件:密码:password,//使用捕获的密码); print('=} on FirebaseAuthException catch(e){ if(e.code == 'weak-password'){ print('The password provided is too weak.');} else if(e.code == 'email-already-in-use'){ print('该电子邮件的帐户已存在。');} } public int findDuplicate(e){} },//.(按钮样式和文本的其余部分)),),
//.
在调用UserWithEmailAndPassword之前,请确保捕获用户的密码输入并将其设置为密码变量。此外,请确保在Flutter应用中正确配置了Firebase,包括必要的Firebase配置文件。

juud5qan

juud5qan2#

请确保,您已启用电子邮件和密码从firebase管理面板,按照下面的步骤
1.打开Firebase控制台帐户。
1.点击所有产品,显示在侧导航栏。
1.要查看身份验证卡,请单击它。
1.滑动标签
登录
方法,然后点击添加提供商按钮。
1.选择电子邮件和密码,请参阅对话框单击以启用。
然后重新启动您的应用程序,并尝试登录也检查日志猫消息
enter image description here

相关问题