簡體   English   中英

Flutter:LateInitializationError:字段“_name”尚未初始化

[英]Flutter: LateInitializationError: Field '_name' has not been initialized

我最近習慣於使用 firebase 核心對我的代碼進行了一些我不太了解的更改。 我是編程新手 flutter。無論如何,我已經嘗試閱讀這個類似的主題,但我仍然不太明白。 有人可以提供解決以下錯誤所需的示例代碼嗎?

Firebase.dart

import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:flutter/material.dart';
import 'package:mybankapp/routscreens/routwidget.dart';

class FirebaseAuthMethods {

  final _firestore = FirebaseFirestore.instance;
  final _firebaseAuth = FirebaseAuth.instance;



  //Email Registration
  Future<void> signUpWithEmail({
    required String name,
    required String email,
    required String password,
    
  }) async {
    
      await _firebaseAuth.createUserWithEmailAndPassword(
        email: email,
        password: password,
      );
      await sendEmailVerification();
      await _firestore
        .collection('users')
        .doc(FirebaseAuth.instance.currentUser!.uid)
        .set({
      'Name': name,
      'email': email,
    });
     
  }

  //Email Login
  Future<void> loginWithEmail({
    required String email,
    required String password,
  }) async {
    try{
      await _firebaseAuth.signInWithEmailAndPassword(
        email: email,
        password: password,
      );
      if (!_firebaseAuth.currentUser!.emailVerified){
        await sendEmailVerification();
        //show mail not verified and mail verification is sent again.
      }else {
        NavigationBarBottom();
        //Show Home Page
      }
    } on FirebaseAuthException catch (e){
      e.message!;
      //show snackbar for error mwssage
    } 
  }


  //Email Verification
  Future<void> sendEmailVerification() async{
    try{
      _firebaseAuth.currentUser!.sendEmailVerification();
      //Snackbar for Verification Mail
    } on FirebaseAuthException catch(e){
      //Snackbar for error email msg
    }
  }
}

注冊頁面.dart

import 'package:flutter/gestures.dart';
import 'package:flutter/material.dart';
import 'package:get/get.dart';
import 'package:mybankapp/authscreens/loginscreen.dart';
import 'package:mybankapp/colors/colors.dart';
import 'package:mybankapp/routscreens/routwidget.dart';
import 'package:mybankapp/textfontfamily/textfontfamily.dart';
import 'package:mybankapp/welcomescreen/welcomescreen.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:mybankapp/firebase_services/firebase_auth';

class SignUpScreen extends StatefulWidget {
  @override
  _SignUpScreenState createState() => _SignUpScreenState();
}

class _SignUpScreenState extends State<SignUpScreen> {
  final _formKey = GlobalKey<FormState>();
  final FirebaseAuthMethods firebaseAuthMethods = FirebaseAuthMethods();
  late String _name;
  late String _emailAddress = '';
  late String _password;
  late String _confirmPassword;

  final bool _isLoading = false;


  void signUpUser() async {
    try {
      firebaseAuthMethods.signUpWithEmail(
        name: _name,
        email: _emailAddress,
        password: _password,
      );
    } on FirebaseAuthException catch (e) {
      print(e.message!);
      //Snackbar for error mail
    }
    //NavigationBarBottom();
  }

  Text text(String text) {
    return Text(
      text,
      style: TextStyle(
        fontSize: 10,
        fontFamily: TextFontFamily.helveticaNeueCyrRoman,
        color: ColorResources.white,
      ),
    );
  }

  TextFormField textFormField(String hint, String? Function(String?) validator,
      void Function(String?) onSaved,
      {bool obscureText = false}) {
    return TextFormField(
      style: TextStyle(
        fontFamily: TextFontFamily.helveticaNeueCyrRoman,
        fontSize: 13,
        color: ColorResources.grey2,
      ),
      obscureText: obscureText,
      cursorColor: ColorResources.blue1,
      decoration: InputDecoration(
        filled: true,
        fillColor: ColorResources.grey1.withOpacity(0.05),
        hintText: hint,
        isDense: true,
        hintStyle: TextStyle(
          fontFamily: TextFontFamily.helveticaNeueCyrRoman,
          fontSize: 13,
          color: ColorResources.grey2,
        ),
        enabledBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(5),
          borderSide: BorderSide(
            width: 1,
            color: ColorResources.blue1.withOpacity(0.6),
          ),
        ),
        border: OutlineInputBorder(
          borderRadius: BorderRadius.circular(5),
          borderSide: BorderSide(
            width: 1,
            color: ColorResources.blue1.withOpacity(0.6),
          ),
        ),
        errorBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(5),
          borderSide: BorderSide(
            width: 1,
            color: ColorResources.blue1.withOpacity(0.6),
          ),
        ),
        focusedBorder: OutlineInputBorder(
          borderRadius: BorderRadius.circular(5),
          borderSide: BorderSide(
            width: 1,
            color: ColorResources.blue1.withOpacity(0.6),
          ),
        ),
      ),
      validator: validator,
      onSaved: onSaved,
    );
  }

 
  // emailAddress validation
  // ignore: valid_regexps
  final _emailAddressRegExp =
      RegExp(r'^.+@[a-zA-Z]+\.{1}[a-zA-Z]+(\.{0,1}[a-zA-Z]+)$');

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      backgroundColor: ColorResources.backGroundColor,
      body: SingleChildScrollView(
        child: Padding(
          padding: const EdgeInsets.only(top: 50, left: 15, right: 15),
          child: Column(
            crossAxisAlignment: CrossAxisAlignment.start,
            children: [
              InkWell(
                onTap: () {
                  Get.off(WelcomeScreen());
                },
                child: Icon(
                  Icons.close,
                  color: ColorResources.white,
                ),
              ),
              SizedBox(height: 70),
              Text(
                "Create Account",
                style: TextStyle(
                    fontFamily: TextFontFamily.helveticNeueCyrBold,
                    fontSize: 35,
                    color: ColorResources.red),
              ),
              SizedBox(height: 7),
              Text(
                "Open a Noble Bank account with a few details.",
                style: TextStyle(
                    fontFamily: TextFontFamily.helveticaNeueCyrRoman,
                    fontSize: 15,
                    color: ColorResources.white1),
              ),
              SizedBox(height: 40),
              Form(
                key: _formKey,
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    text("Full name"),
                    SizedBox(height: 10),
                    textFormField("", (value) {
                      if (value!.isEmpty) {
                        return "Please enter your name";
                      }
                      return null;
                    }, (value) {
                      _name = value!;
                    }),
                    SizedBox(height: 20),
                    text("Email Address"),
                    SizedBox(height: 10),
                    textFormField("", (value) {
                      if (!_emailAddressRegExp.hasMatch(value!)) {
                        return "Please enter your email address";
                      }
                      return null;
                    }, (value) {
                      _emailAddress = value!;
                    }),
                    SizedBox(height: 20),
                    text("Password"),
                    SizedBox(height: 10),
                    textFormField("", (value) {
                      if (value!.isEmpty) {
                        return "Please enter your password";
                      } else if (value.length < 8) {
                        return "Password must be at least 8 characters long";
                      }
                      return null;
                    }, (value) {
                      _password = value!;
                    }, obscureText: true),
                    SizedBox(height: 20),
                    text("Repeat password"),
                    SizedBox(height: 10),
                    textFormField("", (value) {
                      if (value!.isEmpty) {
                        return "Please enter your password";
                      } else if (value != _password) {
                        return "Password doesn't match";
                      }
                      return null;
                    }, (value) {
                      _confirmPassword = value!;
                    }, obscureText: true),
                  ],
                ),
              ),
              SizedBox(height: Get.height >= 876 ? 150 : 50),
              _isLoading
                  ? CircularProgressIndicator()
                  : SizedBox(
                      width: double.infinity,
                      child: InkWell(
                        onTap: signUpUser,
                        child: Container(
                          height: 50,
                          width: Get.width,
                          decoration: BoxDecoration(
                            color: ColorResources.red,
                            borderRadius: BorderRadius.circular(10),
                          ),
                          child: Center(
                            child: Text(
                              "CREATE YOUR FREE ACCOUNT",
                              style: TextStyle(
                                  fontFamily:
                                      TextFontFamily.helveticaNeueCyrRoman,
                                  fontWeight: FontWeight.w700,
                                  fontSize: 13.5,
                                  color: ColorResources.white),
                            ),
                          ),
                        ),
                      ),
                    ),
              SizedBox(height: 20),
              Center(
                child: RichText(
                  text: TextSpan(
                    text: "Do you already have a Noble Bank account?",
                    style: TextStyle(
                      fontSize: 13.5,
                      fontWeight: FontWeight.w300,
                      fontFamily: TextFontFamily.helveticaNeueCyrRoman,
                      color: ColorResources.white2,
                    ),
                    children: <TextSpan>[
                      TextSpan(
                        recognizer: TapGestureRecognizer()
                          ..onTap = () => Get.to(LogInScreen()),
                        text: "  Sign in here",
                        style: TextStyle(
                          fontSize: 14,
                          fontFamily: TextFontFamily.helveticaNeueCyrRoman,
                          fontWeight: FontWeight.w300,
                          color: ColorResources.red,
                        ),
                      ),
                    ],
                  ),
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }
}

如果您不能保證在調用signUpUser()之前將_name (和其他字段)設置為有效值,則不應將late設置為 .

相反,使它們可以為空,如

String? _name;

並在使用數據創建用戶帳戶之前檢查非空值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM