【问题标题】:The method [] was called on Null while syncing Firestore using Flutter使用 Flutter 同步 Firestore 时在 Null 上调用了方法 []
【发布时间】:2019-12-06 17:44:22
【问题描述】:

我在尝试同步用户硬币时遇到了这个错误:方法 [] 在 Null 上被调用。如何使用 Firestore 动态显示他的硬币?

 Widget firestoreBuild2(BuildContext context) {
    return StreamBuilder(
      stream: Firestore.instance.collection('users').document('id').snapshots(),
      builder: (context, snapshot) {
        if (snapshot.hasError)
          return  Text('Error: ${snapshot.error}');
        switch (snapshot.connectionState) {
          case ConnectionState.waiting: return  Text('Loading...');
          default:
            var userDocument = snapshot.data;
            return  Text(
            userDocument["coins"],
            textAlign: TextAlign.center,
            style: TextStyle(
              fontFamily: AppTheme2.fontName,
              fontWeight: FontWeight.normal,
              fontSize: 24,
              letterSpacing: 0.0,
              color: AppTheme2.white,
           ),
          ); 
        }
      },
    );
  }
}

【问题讨论】:

    标签: firebase flutter google-cloud-firestore


    【解决方案1】:

    原来发生这种情况的原因是因为我获取的是字符串 'id' 而不是我的变量 id,这就是导致 null 错误的原因。

    【讨论】:

      【解决方案2】:

      snapshot.connectionState 有四个可能的值:none、waiting、active 或 done。我不确定连接状态与快照是否有数据之间的关系究竟是什么。

      但您可以做的一件事是检查是否为 snapshot.hasData,如果 snapshot.data 为 null,它将返回 false。

      Widget firestoreBuild2(BuildContext context) {
          return StreamBuilder(
            stream: Firestore.instance.collection('users').document('id').snapshots(),
            builder: (context, snapshot) {
              if (!snapshot.hasData)
                return  Text('Loading ...');
      
              var userDocument = snapshot.data;
              return  Text(
                userDocument["coins"],
                textAlign: TextAlign.center,
                style: TextStyle(
                  fontFamily: AppTheme2.fontName,
                  fontWeight: FontWeight.normal,
                  fontSize: 24,
                  letterSpacing: 0.0,
                  color: AppTheme2.white,
                ), 
              );
            },
          );
        }
      }
      

      【讨论】:

      • 试过这个但没有用。向我展示了同样的错误。还有其他建议吗?
      猜你喜欢
      • 2020-06-07
      • 2019-03-10
      • 2020-11-06
      • 2019-09-23
      • 2020-06-04
      • 2021-09-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多