【问题标题】:Dart/Flutter// "The method 'toDate' was called on null. Receiver: null Tried calling: toDate()"Dart/Flutter//“方法 'toDate' 在 null 上被调用。接收者:null 尝试调用:toDate()”
【发布时间】:2021-07-31 09:49:18
【问题描述】:

我正在尝试使用 toDate() 将时间戳从 firebase 转换为 DateTime。

return StreamBuilder<List<Contact>>(
      stream:DBService.instance.getUsersInDB(_searchText) ,
        builder: (context, _snapshot){
        var _usersData = _snapshot.data;
      return _snapshot.hasData ? Container(
        height :MediaQuery.of(context).size.height * 0.75,
        child: ListView.builder(
          itemCount: _usersData.length,
          itemBuilder: (BuildContext _context,
              int _index){
            var _userData = _usersData[_index];
           var _currentTime = DateTime.now();
            var _isUserActive = _userData.lastseen.toDate().isBefore(  //ERROR
              _currentTime.subtract(Duration(hours: 1),
              ),
            );
            return ListTile(
              title: Text(_userData.name),
              leading: Container(
                width: 50,
                height: 50,
                decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(100),
                  image: DecorationImage(
                    fit: BoxFit.cover,

我遇到了这个错误;

'以下 NoSuchMethodError 被抛出构建: 在 null 上调用了方法“toDate”。 接收方:空 尝试调用:toDate() ' 有谁知道如何解决这个问题?

提前致谢

【问题讨论】:

    标签: firebase flutter dart google-cloud-firestore


    【解决方案1】:

    变量 lastseen 为空,您正试图对其调用方法。尝试使用?.?? 等可识别空值的运算符来防止可能出现的空值,请参阅here

                var _isUserActive = _userData?.lastseen?.toDate()?.isBefore(  
                  _currentTime.subtract(Duration(hours: 1),
                  ),
     )??false;
    

    通过使用?.,我们可以防止您遇到的错误,并且使用??,如果最后一个方法/属性的计算结果为null,我们会将值分配给_isUserActive

    还要检查您是否在 UserData 中的此方法 toDate() 内正确转换。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-07-03
      • 2020-06-11
      • 1970-01-01
      • 2020-01-29
      • 1970-01-01
      相关资源
      最近更新 更多