方法'[]'在null上被调用。接收方:null尝试调用:[](“ color”)

时间:2020-08-17 09:35:51

标签: firebase flutter dart google-cloud-firestore

我想从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)下的info,因此该名称最初为null,因此当其null时,要访问document(widget.rackBookItems.id)中的颜色信息。 让我知道是否需要更多信息以获得解决方案。

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

enter image description here

完成某些任务后,数据库将其更改为以下一项,因此cardColor更改为true,并且颜色也可以从document(_userId)中访问

enter image description here 错误:

enter image description here

1 个答案:

答案 0 :(得分:3)

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