I’ve been trying to achieve online status in my FlutterFlow app by using Flutter and Firestore. (not Realtime Database)
On addition to AppLifeCycleState conditions below, I need to add these 2 conditions:
1- if user is logged in, set status to “online”
2- if user is logged out, set status to “offline”
class OnlineStatus extends StatefulWidget {
const OnlineStatus({
super.key,
required this.userId,
});
final String userId;
@override
State<OnlineStatus> createState() => _OnlineStatusState();
}
class _OnlineStatusState extends State<OnlineStatus>
with WidgetsBindingObserver {
String _userStatus = 'offline';
@override
void initState() {
super.initState();
WidgetsBinding.instance.addObserver(this);
_updateUserStatus('online');
_listenToUserStatus();
}
@override
void didChangeAppLifecycleState(AppLifecycleState state) {
if (state == AppLifecycleState.paused ||
state == AppLifecycleState.inactive) {
_updateUserStatus('offline');
} else if (state == AppLifecycleState.resumed) {
_updateUserStatus('online');
}
}
Future<void> _updateUserStatus(String status) async {
await FirebaseFirestore.instance
.collection('Users')
.doc(widget.userId)
.update({'status': status});
}
void _listenToUserStatus() {
FirebaseFirestore.instance
.collection('Users')
.doc(widget.userId)
.snapshots()
.listen((snapshot) {
setState(() {
_userStatus = snapshot.data()?['status'] ?? 'offline';
});
});
}
@override
Widget build(BuildContext context) {
return _buildStatusCircle();
}
Widget _buildStatusCircle() {
Color circleColor = (_userStatus == 'online') ? Colors.green : Colors.red;
return Container(
width: 12,
height: 12,
decoration: BoxDecoration(
color: circleColor,
shape: BoxShape.circle,
),
);
}
}
I was using AppLifecycleState.detached for changing status to “offline” but it wasn’t working so I had to change it to AppLifecycleState.inactive. Would also love to know why it didn’t work.
Also wonder if using Firestore Database would be a big loss compared to Realtime Database.
I tried adding a condition something like FirebaseAuth.instance.currentUser != null but didn’t work.
Although my code seems to be working I’m just not sure if this is the best way to do this so I can take feedback to change it.
johndoe is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.