«Получатель« uid »не определен для класса« AuthResult »» при попытке использовать .createUserWithEmailAndPassword - PullRequest
0 голосов
/ 09 января 2020

Я довольно новичок в разработке приложений, и у меня возникла проблема с одной ошибкой в ​​моем коде.

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],
        ),
      ),
    );
  }
}

Я получаю сообщение об ошибке: «Идентификатор получателя uid» не определен для класса «AuthResult» »всякий раз, когда существует« currentUser.uid ». Я использовал код из https://github.com/samsam-026/flutter-example/tree/master/lib, поэтому я не уверен, почему он не работает. Я пробовал getUid (), но я не уверен, правильно ли я это делаю, потому что он все равно выдает ошибку. Любые советы приветствуются. Спасибо!

enter image description here

1 Ответ

3 голосов
/ 09 января 2020

При последних обновлениях (после v0.12.0) обновления плагина 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(),
               }));
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...