I'm trying to convert the timestamp from firebase to DateTime using toDate().

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,

I'm having this error;

'The following NoSuchMethodError was thrown building: The method 'toDate' was called on null. Receiver: null Tried calling: toDate() ' Does anyone know how to solve the issue?

Thanks in advance


Solution 1: croxx5f

The variable lastseen is null and you are attempting to call a method on it. Try to guard you against possible nulls using the null aware operators like ?. or ?? see here:

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

By using ?. we prevent the error you are getting and using ?? we assign to _isUserActive the value false if the last method/attribute evaluates to null.

Do check also if you are correctly converting inside this method toDate() in UserData.