【问题标题】:The method '[]' was called on null. Receiver: null Tried calling: []("color")在 null 上调用了方法“[]”。接收方:null 尝试调用:[]("color")
【发布时间】:2020-12-06 10:25:35
【问题描述】:

我想从 Firestore 中检索颜色。但每次我这样做时都会出现以下错误:

The method '[]' was called on null.
Receiver: null
Tried calling: []("color")

这是我的代码:

 bool cardColor = false;
  String _userId;

  @override
  void initState() {
    super.initState();
    checkIfColorOrNot();
  }

  checkIfColorOrNot() async {
    FirebaseAuth.instance.currentUser().then((user) {
      _userId = user.uid;
    });
    DocumentSnapshot ds = await Firestore.instance
        .collection('rackBookItems')
        .document(widget.rackBookItems.id)
        .collection('user')
        .document(_userId)
        .get();
    this.setState(() {
      cardColor = ds.exists; // If the above if exists then cardColor  is turned true else it stays flase
    });
  }

  

_cardColorApply(child) {
    FirebaseAuth.instance.currentUser().then((user) {
      _userId = user.uid;
    });
    return StreamBuilder(
      stream: cardColor 
          ? Firestore.instance
              .collection('rackBookItems')
              .document(widget.rackBookItems.id)
              .collection('user')
              .document(_userId)
              .snapshots() // this should be shows only when cardColor is true
          : Firestore.instance
              .collection('rackBookItems')
              .document(widget.rackBookItems.id)
              .snapshots(), // this should be shows only when cardColor is false
      builder: (context, snapshot) {
        
       //Check to make sure snapshot.hasData has data or not 
        if (!snapshot.hasData) {
          return CircularProgressIndicator();
        }
        int colorValue = int.parse(snapshot.data['color']);
        return Card(
          color: Color(colorValue),
          child: child,
        );
      },
    );
  }



@override
      Widget build(BuildContext context) {
        return InkWell(
          onTap: widget.onTap,
          child: _cardColorApply(_listItems()),
        );
      }

我为此使用 statefull 小部件。 document(_userId) 下的信息是最后添加的,因此最初为 null,因此当它的 null 想要访问 document(widget.rackBookItems.id) 以获取颜色信息时。 如果需要更多信息来获得解决方案,请告诉我。

当 cardColor = false 我的数据库将是这样的,因此它可以从 文档(widget.rackBookItems.id)

完成一些任务后,数据库更改为下面的一个,因此 cardColor 更改为 true,并且可以从 document(_userId) 访问颜色

错误:

【问题讨论】:

  • 它说 snapshot.data 为空。你能告诉我们你的数据库是什么样的吗?
  • 是的,我已经添加了您要求的数据库截图。
  • 我的意思是你的数据库结构。您可以尝试打印出 snapshot.data 以检查其是否为空吗?
  • 当我给 print(snapshot.data);它显示了这一点:I/flutter (31146): 'DocumentSnapshot' 的实例
  • 试试这个!snapshot.hasData && snapshot.data.isNotEmpty

标签: firebase flutter dart google-cloud-firestore


【解决方案1】:

_userId 正在返回 null,这就是您没有获得任何数据的原因。您需要创建以下方法:

  Stream<DocumentSnapshot> getUserDocument() async* {
    FirebaseUser user = await getCurrentUser();
    yield* Firestore.instance
        .collection('rackBookItems')
        .document(widget.rackBookItems.id)
        .collection('user')
        .document(user.uid)
        .snapshots();
  }


  Stream<DocumentSnapshot> getRackDocument() async* {
    yield* Firestore.instance
        .collection('rackBookItems')
        .document(widget.rackBookItems.id)
        .snapshots();
  }

  Future<FirebaseUser> getCurrentUser() async {
    return await FirebaseAuth.instance.currentUser();
  }

然后在checkIfColorOrNot()里面添加获取文档的回调里面,确保获取到userId之后执行:

  checkIfColorOrNot() async {
    FirebaseAuth.instance.currentUser().then((user) {
      _userId = user.uid;
      DocumentSnapshot ds = await Firestore.instance
          .collection('rackBookItems')
          .document(widget.rackBookItems.id)
          .collection('user')
          .document(_userId)
          .get();
      this.setState(() {
        cardColor = ds.exists; // If the above if exists then cardColor  is turned true else it stays flase
      });
    });
  }

StreamBuilder 中执行以下操作:

_cardColorApply(child) {
    return StreamBuilder(
      stream: cardColor ? getUserDocument() : getRackDocument(),
      builder: (context, snapshot) {
        if (!snapshot.hasData) {
          return CircularProgressIndicator();
        }
       else if(snapshot.hasData){
        int colorValue = int.parse(snapshot.data['color']);
        return Card(
          color: Color(colorValue),
          child: child,
        );
      }

【讨论】:

  • 感谢彼得的帮助。但是有一个小问题,我不再收到错误,但应用程序没有按照我的意愿进行操作。 cardColor 为 false 时应显示 getRackDocument() 中的颜色,当 cardColor 为 true 时应显示 getUserDocument() 中的颜色,当前 cardColor 即使它为 true 也显示 getRackDocument() 中的颜色。你能帮我解决这个问题吗?
  • 方法里面_cardColorApply(child) {可以吗print(cardColor)
  • cardColor 即使在 Firestore 中生成,仍然显示为 false。在此 cod 中生成的另一件事 user.uid 与在 firebase 中生成的用户 ID 不匹配。知道如何解决这个问题吗?
  • 在您的代码中,您正在执行 document(_userId),这意味着您正在将当前登录的用户 ID 分配给文档。因此,在数据库中,您应该将用户 ID 作为文档 ID...如果你没有,那么你需要改变你的数据库
  • 没错。我有我的用户 ID 作为存储在 firestore 中的文档 ID。但是当我 print(_userId) 这并没有给出当前的用户 ID。仍在弄清楚出了什么问题。
猜你喜欢
  • 2021-08-26
  • 2021-01-14
  • 2020-05-24
  • 2022-08-05
  • 2021-04-17
  • 2020-07-03
  • 2021-03-29
  • 1970-01-01
  • 2022-09-26
相关资源
最近更新 更多