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

标签 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

最佳答案

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

关于firebase - 在空方法上调用了 '[]'方法。接收方:null尝试调用:[] (“color”),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63448221/

相关文章:

android - 如何在 Firebase 类中表示嵌套数据

java - 将适配器设置为回收器 View 时出现空指针异常

ios - 如何在 Xcode 12.4 上运行 iOS 模拟器 10.3.1?

dart - 如何从 Javascript 调用 Dart 程序?

dart - Flutter:实现 Material Search 栏以从服务器异步搜索数据

dart - 如何为 ListView 索引 firestore 文档映射项

java - 如何在回收站 View 中只获取我想要的项目

javascript - Algolia 搜索网络错误

Flutter:FCM 未处理异常:对空值使用空检查运算符

firebase - 使用Flutter可以从哪里获得SHA-1证书指纹? (使用flutter create --androidx ProjectName)