Skip to content

Instantly share code, notes, and snippets.

@kmartins
Created February 20, 2021 00:27
Show Gist options
  • Select an option

  • Save kmartins/29a6e4926fbd016deeeaffd3c5fd1c6a to your computer and use it in GitHub Desktop.

Select an option

Save kmartins/29a6e4926fbd016deeeaffd3c5fd1c6a to your computer and use it in GitHub Desktop.
import 'dart:async';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
void main() {
WidgetsFlutterBinding.ensureInitialized();
SystemChrome.setPreferredOrientations([
DeviceOrientation.portraitUp,
]).then((_) {
runApp(MaterialApp(
debugShowCheckedModeBanner: false,
home: MyHomePage(),
));
});
}
class MyHomePage extends StatefulWidget {
@override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
StreamSubscription<Event> subscription;
DatabaseReference connectedlistRef = FirebaseDatabase.instance.reference().child('.info/connected');
//connectedlistRef contains all the user's UIDs currently connected to firebase realtime database
//here we are making the connection to the firebase by Subscribing to "connectedlistRef"
//we can subscribe to any other referece childs too.but to avoid data we use the path=> (.info/connected) [AFAIK]
DatabaseReference myidRef = FirebaseDatabase.instance.reference().child('users/mymobilenumber');
bool localIOnlineIndicator = false;//just to indicate you are online or offline on your Homepage
@override
void initState() {
subscription = connectedlistRef.onValue.listen(handlerFunction);
//subscribes to Rtdb and monitors either we are connected or not
//the handlerFunction handles What to do when we are disconnected or connected
super.initState();
}
@override
void dispose() {
subscription?.cancel();//canceling to avoid leaks
super.dispose();
}
@override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Home Page'),
actions: <Widget>[
IconButton(
icon: Icon(
Icons.brightness_1,
color: localIOnlineIndicator ? Colors.green : Colors.grey,//green shows that you are Online
),
onPressed: () async {
localIOnlineIndicator
? await FirebaseDatabase.instance.goOffline()//Manually sets Offline by disconnecting ourselfs from Firebase
: FirebaseDatabase.instance.goOnline();//Manually set Online by Re connecting to Firebase database
},
),
],
));
}
void handlerFunction(Event event) {
DataSnapshot dataSnapshot = event.snapshot;
bool myStatus = dataSnapshot.value;// (.info/connected) returns true if you are connected to Firebase otherwise it will be false
if (myStatus == false) {
setState(() {
localIOnlineIndicator = false;
});
}
//in case you are not online and opened your app without internet just it does nothing.
else {
//else if you turned on internet and connected to Firebase
//First of All we need to tell firebase What to do if we lost Internet
//then only we Online = true
//So here i tell firebase If i lost connection please set "o=false" and "ls:198793427892893923" [timestamp]
//To reduce the downloading data I used "o" instead of "online" and "ls" instead of "last seen"
myidRef.onDisconnect().set({
'o': false,
'ls': ServerValue.timestamp,
})
//once the above statement is acknowledged by firebase then we are setting ourself Online = true
.then((a) {
myidRef.update({
'o': true,
'ls': ServerValue.timestamp
});
});
setState(() {
localIOnlineIndicator = true;
});
}
}
//TODO Please note the Offline will not be updated immediately after you turned of internet
// it will take 2 to 3 minutes to set offline
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment