本文介绍了Flutter:未处理的异常:NoSuchMethodError:在 null 上调用了 getter 'id'.接收者:空尝试调用:id的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm having issues setting up signing up with an email and password using Flutter. I got it to sign the new user in and it saves their Firebase authentication info but it doesn't save any profile data to the Firebase Storage section. I'm not sure what I'm doing wrong here, I don't understand why id is null. Some help and guidance would be really appreciated!

这是我得到的错误

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

这是来自 user.dart

This is from user.dart

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

这是来自 Signup.dart

This is from Signup.dart

错误指向 usersReference.document 行.

The error pointed to the usersReference.document line.

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

This is from Timeline.dart

错误指向这两种方法的两条 QuerySnapshot 行.

The error pointed to both of the QuerySnapshot lines from those two methods.

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();
    });
  }

如果我遗漏了什么,请告诉我,这可能会有所帮助.

Please let me know if I left anything out, that may help.

推荐答案

currentUser 为 null,因为您没有初始化该类.例如:

currentUser is null because you didn't initialize the class. For example:

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

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

Of course the above code still wont work, because id is equal to null. If the document id in your database is equal to the user uid, then do the following:

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 Authentication 获得用户的 uid ,然后因为你使用可选的命名参数,你可以用 初始化 User 类id 属性并在 document() 方法中使用它.

So here you get the uid of the user from Firebase Authentication and then since you are using optional named parameter, you can initialize the User class with the id property and use it inside the document() method.

这篇关于Flutter:未处理的异常:NoSuchMethodError:在 null 上调用了 getter 'id'.接收者:空尝试调用:id的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 15:29