【问题标题】:"The getter 'uid' isn't defined for the class 'AuthResult'" when trying to use .createUserWithEmailAndPassword尝试使用 .createUserWithEmailAndPassword 时,“没有为类 'AuthResult' 定义 getter 'uid'”
【发布时间】:2020-04-26 14:34:46
【问题描述】:

我对应用程序开发相当陌生,并且在我的代码中遇到一个错误。

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

void main() => runApp(Signup());

//Stateless: Cannot be changed during runtime
//Can only be called once
class Signup extends StatelessWidget {
  
  @override
  
  Widget build(BuildContext context) {
    return MaterialApp(
      debugShowCheckedModeBanner: false,
      theme: ThemeData(
        primaryColor: Colors.pink,
      ),
      home: SignUp(title: 'Sign up!'),
    );
  }
}


class SignUp extends StatefulWidget {
  SignUp({Key key, this.title, this.uid}) : super(key: key);

  final String title;
  final String uid;

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

class _SignUpState extends State<SignUp> {
  
  TextStyle style = TextStyle(fontFamily: 'Montserrat', fontSize: 20.0);

 
  TextEditingController first_entry = new TextEditingController();
  TextEditingController last_entry = new TextEditingController();
  TextEditingController email_entry = new TextEditingController();
  TextEditingController password_entry = new TextEditingController();

  PersistentBottomSheetController _sheetController;
  bool _loading = false;

  @override
  Widget build(BuildContext context) {
    
    final FirstName = TextFormField(
      controller: first_entry,
      validator: (value) {
        if(value.isEmpty){
          return 'Please enter your first name';
        }
        return null;
      },
      obscureText: false,
      style: style,
      decoration: InputDecoration(
          labelText: "First Name",
          contentPadding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
          border:
          OutlineInputBorder(borderRadius: BorderRadius.circular(32.0))),
    );

    final LastName = TextFormField(
      controller: last_entry,
      validator: (value) {
        if(value.isEmpty){
          return 'Please enter your last name';
        }
        return null;
      },
      style: style,
      decoration: InputDecoration(
          labelText: "Last Name",
          contentPadding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
          border:
          OutlineInputBorder(borderRadius: BorderRadius.circular(32.0))),
    );

    final email = TextFormField(
      controller: email_entry,
      validator: (value) {
        if(value.isEmpty){
          return 'Please enter your email';
        }
        return null;
      },
      style: style,
      decoration: InputDecoration(
          labelText: "Email",
          contentPadding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
          border:
          OutlineInputBorder(borderRadius: BorderRadius.circular(32.0))),
    );

    final pass = TextFormField(
      controller: password_entry,
      obscureText: true,
      validator: (value) {
        if(value.isEmpty){
          return 'Please enter your password';
        }
        return null;
      },
      style: style,
      decoration: InputDecoration(
          labelText: "Password",
          contentPadding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
          border:
          OutlineInputBorder(borderRadius: BorderRadius.circular(32.0))),
    );

    final Signingup = Material(
      elevation: 5.0,
      borderRadius: BorderRadius.circular(30.0),
      color: Color(0xff01A0C7),
      child: MaterialButton(
        minWidth: MediaQuery.of(context).size.width,
        padding: EdgeInsets.fromLTRB(20.0, 15.0, 20.0, 15.0),
        onPressed: () async {
          print(first_entry.text);
          print(last_entry.text);
          print(email_entry.text);
          try {
           FirebaseAuth.instance
               .createUserWithEmailAndPassword(
                  email: email_entry.text,
                  password: password_entry.text)
               .then((authResult) => Firestore.instance
                  .collection("users")
                  .document(authResult.user.uid)
                  .setData({
                    "uid": authResult.user.uid,
                    "fname": first_entry.text,
                    "surname": last_entry.text,
                    "email": email_entry.text,
           })
           .then((result) =>  {
               Navigator.pushAndRemoveUntil(
               context,
               MaterialPageRoute(
                   builder: (context) => MyHomePage(
                     title:
                     first_entry
                         .text +
                         "'s Tasks",
                     uid: authResult.user.uid,
                   )),
                   (_) => false),
               first_entry.clear(),
               last_entry.clear(),
               email_entry.clear(),
               password_entry.clear(),
               }));
            setState(() {});
            Navigator.push(
              context,
              MaterialPageRoute(builder: (context) => new MyHomePage()),
            );
            }
          catch (e) {
            print('Error while logging in $e'); // #debug
          }
        },
        child: Text("Sign me up!",
            textAlign: TextAlign.center,
            style: style.copyWith(
                color: Colors.white, fontWeight: FontWeight.bold)),
      ),
    );
    return Scaffold(
     body: SingleChildScrollView(
        child: Center(
          child: Container(
            color: Colors.white,
            child: Padding(
              padding: const EdgeInsets.all(36.0),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.center,
                mainAxisAlignment: MainAxisAlignment.center,
                children: <Widget>[
                  SizedBox(
                    height: 235.0,
                    child: Image.asset(
                      "images/SignUp.png",
                      fit: BoxFit.contain,
                    ),
                  ),
                  FirstName,
                  SizedBox(height: 25.0),
                  LastName,
                  SizedBox(height: 25.0),
                  email,
                  SizedBox(height: 25.0),
                  pass,
                  SizedBox(height: 39.0),
                  Signingup,
                  SizedBox(height: 25.0),
                ],
              ),
            ),
          ),
        ),
      ),
      appBar: AppBar(
        title: Text(widget?.title ?? ''),
      ),
      bottomNavigationBar: BottomAppBar(
        child: Container(
          height: 45.0,
          color: Colors.pink[100],
        ),
      ),
    );
  }
}

每当有“currentUser.uid”时,我得到的错误是“没有为类 'AuthResult' 定义 getter 'uid'”。我使用了来自https://github.com/samsam-026/flutter-example/tree/master/lib 的代码,所以我不确定它为什么不起作用。我已经尝试过 getUid(),但我不确定我是否做得对,因为它仍然给我一个错误。任何提示表示赞赏。谢谢!

【问题讨论】:

    标签: firebase flutter dart firebase-authentication


    【解决方案1】:

    随着最近更新 (after v0.12.0) of firebase_auth 插件更新,登录方法返回 AuthResult 而不是 FirebaseUser,因此您必须从 authresult 获取用户。

               FirebaseAuth.instance
                   .createUserWithEmailAndPassword(
                      email: email_entry.text,
                      password: password_entry.text)
                   .then((authResult) => Firestore.instance
                      .collection("users")
                      .document(authResult.user.uid) //returns auth result so you should get user.uid from auth result
                      .setData({
                        "uid": authResult.user.uid,
                        "fname": first_entry.text,
                        "surname": last_entry.text,
                        "email": email_entry.text,
               })
               .then((result) =>  {
                   Navigator.pushAndRemoveUntil(
                   context,
                   MaterialPageRoute(
                       builder: (context) => MyHomePage(
                         title:
                         first_entry
                             .text +
                             "'s Tasks",
                         uid: authResult.user.uid,
                       )),
                       (_) => false),
                   first_entry.clear(),
                   last_entry.clear(),
                   email_entry.clear(),
                   password_entry.clear(),
                   }));
    

    【讨论】:

    • 哦,哇,效果很好,谢谢。我永远不会得到那个!你会碰巧知道我的代码是否有问题吗?我能够运行它,但是当我尝试将名字和姓氏保存到我的 firebase 数据库时,它没有保存。如果没有,我总是可以再问一个问题!
    • 当然,我编辑了我的问题。我添加了整个注册按钮代码,这是我更改为合并 firebase 的唯一代码(在我的主页中,我只添加了最终字符串 uid,因此我可以在此代码中使用 uid)。我还添加了名字条目的示例。电子邮件、密码和姓氏等其他条目非常相似。如果您需要更多代码,请告诉我!谢谢你的时间,我已经卡了很长一段时间了
    • 完整的可运行代码会有所帮助,但是 1. 您是否登录并检查控制器是否提供输入的值 2. 如果保存了 uid,您是否检查了数据库中保存的内容?(截图数据库会很有帮助)如果保存了 uid 并且只有 fname 和 lname 为空,那么您没有从文本字段中获得正确的值
    • 现在我有一个奇怪的问题,我试图从 TextFormField 打印我的值并添加了 print(first_entry.text);打印(last_entry.text);打印(email_entry.text);就在 onPressed: () async { 然后我在 Android-Studio 的终端上运行我的代码,我看到它打印正确,当我检查我的数据库时,我的信息被保存了!我删除了打印语句,下次输入信息时,它没有保存。我发现这很奇怪,因为我只是打印到终端而不是将其保存在任何地方。我也会用代码和截图再次更新我的问题
    • 尝试在按下按钮时将文本字段的值保存在变量中,然后尝试使用断点调试并检查值。
    猜你喜欢
    • 2021-05-21
    • 2021-08-27
    • 2020-01-18
    • 2021-11-22
    • 1970-01-01
    • 2020-08-08
    • 2021-06-08
    • 2021-04-28
    • 1970-01-01
    相关资源
    最近更新 更多