当前位置: 首页 > 知识库问答 >
问题:

颤振:未处理的异常:NoSuchMethodError:对null调用了getter“id”。接收方:null尝试调用:id

栾耀
2023-03-14

我在使用Flutter注册电子邮件和密码时遇到了问题。我用它来注册新用户,它保存了他们的Firebase身份验证信息,但不会将任何配置文件数据保存到Firebase存储部分。我不确定我在这里做错了什么,我不明白为什么id是空的。一些帮助和指导将真的非常感谢!

这就是我犯的错误

Unhandled Exception: NoSuchMethodError: The getter 'id' was called on null.
Receiver: null
Tried calling: id

这是来自用户的。飞奔

import 'package:cloud_firestore/cloud_firestore.dart';

class User {
  final String id;
  final String profileName;
  final String username;
  final String photoUrl;
  final String url;
  final String email;
  final String bio;
  final String createdAt;

  User({
    this.id,
    this.profileName,
    this.username,
    this.photoUrl,
    this.url,
    this.email,
    this.bio,
    this.createdAt,
  });

  factory User.fromDocument(DocumentSnapshot doc) {
    return User(
      id: doc.documentID,
      email: doc['email'],
      username: doc['username'],
      photoUrl: doc['photoUrl'],
      url: doc['url'],
      profileName: doc['profileName'],
      bio: doc['bio'],
      createdAt: doc['createdAt'],
    );
  }
}

这是来自注册。飞奔

错误指向用户引用。文档行。

import 'dart:io';
import 'package:flutter/material.dart';
import 'package:firebase_auth/firebase_auth.dart';
import 'package:cloud_firestore/cloud_firestore.dart';
import 'package:buddiesgram/models/user.dart';
import 'package:buddiesgram/pages/HomePage.dart';
import 'package:shared_preferences/shared_preferences.dart';


class SignupPage extends StatefulWidget {

  static final String id = 'signup_page';
  final DateTime timestamp = DateTime.now();
  User currentUser;

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

class _SignupPageState extends State<SignupPage> {
  final  FirebaseAuth auth = FirebaseAuth.instance;
  final _formKey = GlobalKey<FormState>();
  String username, email, password;
  SharedPreferences preferences;

  checkIfSignedIn() async {
    auth.onAuthStateChanged.listen((user) {

      if (user != null) {
        Navigator.push(context, MaterialPageRoute(builder: (context) => HomePage()));
      }
    });

    @override
    void initState() {
      super.initState();
      this.checkIfSignedIn();
    }
  }

  saveUserInfoToFireStore() async {

    preferences = await SharedPreferences.getInstance();
    DocumentSnapshot documentSnapshot = await usersReference.document(currentUser.id).get();

    if(!documentSnapshot.exists) {
      usersReference.document(currentUser.id).setData({
        "id": currentUser.id,
        "profileName": currentUser.profileName,
        "username": currentUser.username,
        "photoUrl": currentUser.photoUrl,
        "email": currentUser.email,
        "bio": "",
        "timestamp": timestamp,
        "talkingTo": null,
      });

      //Write data to local
      //currentUser = currentUser as User;
      //await preferences.setString("id", currentUser.id);
      //await preferences.setString("profileName", currentUser.profileName);
      //await preferences.setString("photoUrl", currentUser.photoUrl);

      await followersReference.document(currentUser.id).collection("userFollowers").document(currentUser.id).setData({});

      documentSnapshot = await usersReference.document(currentUser.id).get();
    }

    currentUser = User.fromDocument(documentSnapshot);
  }

  signUp() async {
    if(_formKey.currentState.validate()) {
      _formKey.currentState.save();

      try{
        AuthResult authResult = await auth.createUserWithEmailAndPassword(email: email, password: password);
        FirebaseUser signedInUser = authResult.user;
        if(signedInUser != null) {
        saveUserInfoToFireStore();
        }
        Navigator.push(context, MaterialPageRoute(builder: (context) => HomePage()));
      }
      catch(e) {
        print(e);
      }
    }
  }

这是Timeline.dart

该错误指向这两个方法中的两个QuerySnapshot行。

retrieveTimeLine() async {
    QuerySnapshot querySnapshot = await timelineReference.document(currentUser.id)
        .collection("timelinePosts").orderBy("timestamp", descending: true).getDocuments();

    List<Post> allPosts = querySnapshot.documents.map((document) => Post.fromDocument(document)).toList();

    setState(() {
      this.posts = allPosts;
    });
  }

  retrieveFollowings() async {
    QuerySnapshot querySnapshot = await followingReference.document(currentUser.id)
        .collection("userFollowing").getDocuments();

    setState(() {
      followingsList = querySnapshot.documents.map((document) => document.documentID).toList();
    });
  }

如果我遗漏了什么,请让我知道,这可能会有所帮助。

共有2个答案

訾稳
2023-03-14

去付款。省道并启用签出页面的选项

并禁用本机选项

黄和怡
2023-03-14

当前用户为空,因为您没有初始化类。例如:

  saveUserInfoToFireStore() async {
    currentUser = User(); //initialize
    preferences = await SharedPreferences.getInstance();
    DocumentSnapshot documentSnapshot = await usersReference.document(currentUser.id).get();

当然,上面的代码仍然不起作用,因为id等于null。如果数据库中的文档id等于用户uid,则执行以下操作:

User loggedInUser;

  saveUserInfoToFireStore() async {
     var user = FirebaseAuth.instance.currentUser();
     loggedInUser = User(id : user.uid);
    preferences = await SharedPreferences.getInstance();
    DocumentSnapshot documentSnapshot = await usersReference.document(loggedInUser.id).get();

因此,在这里,您可以从Firebase身份验证获得用户的uid,然后由于您使用可选的命名参数,您可以使用id属性初始化User类,并在文档()中使用它方法。

 类似资料: