Skip to content

Instantly share code, notes, and snippets.

@utkarsh-UK
Created April 25, 2020 05:40
Show Gist options
  • Save utkarsh-UK/ffc66658e55cee03eaff45f57a51a723 to your computer and use it in GitHub Desktop.
Save utkarsh-UK/ffc66658e55cee03eaff45f57a51a723 to your computer and use it in GitHub Desktop.
Showing overlays in a StreamBuilder and removing them on a button onPressed and Navigating to next screen
import 'dart:convert';
import 'package:firebase_database/firebase_database.dart';
import 'package:flutter/material.dart';
import 'package:shared_preferences/shared_preferences.dart';
import '../utilities/constants.dart';
import '../widgets/order_map.dart';
class HomeScreen extends StatefulWidget {
static const String routeName = '/home-screen';
@override
_HomeScreenState createState() => _HomeScreenState();
}
class _HomeScreenState extends State<HomeScreen> {
final _awatingButtonKey = GlobalKey();
final _completedButtonKey = GlobalKey();
final _todaysButtonKey = GlobalKey();
final _missedButtonKey = GlobalKey();
OverlayState overlayState;
OverlayEntry overlayAwaitingEntry;
OverlayEntry overlayCompletedEntry;
OverlayEntry overlayTodaysEntry;
OverlayEntry overlayMissedEntry;
String officeName = '', locationCoords = '';
bool isOfficeOn = true;
@override
void initState() {
super.initState();
_getOfficeData().then((_) => setState(() {}));
}
Future<void> _getOfficeData() async {
final prefs = await SharedPreferences.getInstance();
final userData =
json.decode(prefs.getString('userData')) as Map<String, Object>;
officeName = '${userData['office_name']}';
locationCoords = '${userData['lat']} ${userData['long']}';
}
void showOverlay({
@required BuildContext context,
int awaitCount = 0,
int completeCount = 0,
int todaysCount = 0,
int missedCount = 0,
}) {
WidgetsBinding.instance.addPostFrameCallback((duration) {
if (overlayState == null) {
overlayState = Overlay.of(context);
}
Offset awaitingPos;
Offset completedPos;
Offset todaysPos;
Offset missedPos;
RenderBox awaitingBox =
_awatingButtonKey.currentContext.findRenderObject();
awaitingPos = awaitingBox.localToGlobal(Offset.zero);
RenderBox completedBox =
_completedButtonKey.currentContext.findRenderObject();
completedPos = completedBox.localToGlobal(Offset.zero);
RenderBox todaysBox = _todaysButtonKey.currentContext.findRenderObject();
todaysPos = todaysBox.localToGlobal(Offset.zero);
RenderBox missedBox = _missedButtonKey.currentContext.findRenderObject();
missedPos = missedBox.localToGlobal(Offset.zero);
overlayAwaitingEntry = OverlayEntry(
builder: (context) => Positioned(
top: awaitingPos.dy,
left: awaitingPos.dx,
child: CircleAvatar(
radius: 15,
backgroundColor: Colors.white,
child: Text('$awaitCount'),
),
),
);
overlayCompletedEntry = OverlayEntry(
builder: (context) => Positioned(
top: completedPos.dy,
left: completedPos.dx,
child: CircleAvatar(
radius: 15,
backgroundColor: Colors.white,
child: Text('$completeCount'),
),
),
);
overlayTodaysEntry = OverlayEntry(
builder: (context) => Positioned(
top: todaysPos.dy,
left: todaysPos.dx,
child: CircleAvatar(
radius: 15,
backgroundColor: Colors.white,
child: Text('$todaysCount'),
),
),
);
overlayMissedEntry = OverlayEntry(
builder: (context) => Positioned(
top: missedPos.dy,
left: missedPos.dx,
child: CircleAvatar(
radius: 15,
backgroundColor: Colors.white,
child: Text('$missedCount'),
),
),
);
overlayState.insert(overlayAwaitingEntry);
overlayState.insert(overlayCompletedEntry);
overlayState.insert(overlayTodaysEntry);
overlayState.insert(overlayMissedEntry);
});
}
void removeOverlays() {
if (overlayAwaitingEntry != null &&
overlayCompletedEntry != null &&
overlayTodaysEntry != null &&
overlayMissedEntry != null) {
overlayAwaitingEntry?.remove();
overlayAwaitingEntry = null;
overlayCompletedEntry?.remove();
overlayCompletedEntry = null;
overlayTodaysEntry?.remove();
overlayTodaysEntry = null;
overlayMissedEntry?.remove();
overlayMissedEntry = null;
}
}
@override
Widget build(BuildContext context) {
final deviceWidth = MediaQuery.of(context).size.width;
final deviceHeight = MediaQuery.of(context).size.height;
return Scaffold(
appBar: AppBar(
title: Text(
'$officeName',
style: TextStyle(fontWeight: FontWeight.bold),
),
actions: <Widget>[
IconButton(
icon: Icon(Icons.exit_to_app),
tooltip: 'Logout',
onPressed: () async {
overlayAwaitingEntry.remove();
overlayCompletedEntry.remove();
final prefs = await SharedPreferences.getInstance();
prefs.clear();
Navigator.of(context).popAndPushNamed('/login-screen');
},
),
],
),
body: SizedBox(
height: deviceHeight,
width: deviceWidth,
child: SingleChildScrollView(
child: Column(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
children: <Widget>[
StreamBuilder<Event>(
stream: firebaseAdminRef
.child('Office Location')
.child(officeName)
.child('status')
.onValue,
builder: (BuildContext context, AsyncSnapshot<Event> snapshot) {
if (snapshot.hasData) {
if (snapshot.data.snapshot.value == 'Closed') {
isOfficeOn = false;
}
return Container(
width: deviceWidth,
alignment: Alignment.center,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceAround,
children: <Widget>[
Text(
'Office Status',
style: TextStyle(
color: Colors.black,
fontSize: 18.0,
),
),
Switch.adaptive(
value: isOfficeOn,
onChanged: (change) {
if (isOfficeOn) {
setState(() {
isOfficeOn = false;
firebaseAdminRef
.child('Office Location')
.child(officeName)
.update({'status': 'Closed'});
});
} else {
setState(() {
isOfficeOn = true;
firebaseAdminRef
.child('Office Location')
.child(officeName)
.update({'status': 'Open'});
});
}
},
),
],
),
);
} else if (snapshot.hasError) {
return Text(snapshot.error.toString());
}
return Center(
child: CircularProgressIndicator(),
);
},
),
SizedBox(height: 30),
StreamBuilder<Event>(
stream: firebaseAdminRef
.child('Office Location')
.child(officeName)
.onValue,
builder: (BuildContext context, AsyncSnapshot<Event> snapshot) {
if (snapshot.hasData) {
int awaitCount = int.tryParse(
'${snapshot.data.snapshot.value['awaiting_order_counter']}');
int completeCount = int.tryParse(
'${snapshot.data.snapshot.value['completed_order_counter']}');
int todaysCount = int.tryParse(
'${snapshot.data.snapshot.value['todays_orders']}');
int missedCount = int.tryParse(
'${snapshot.data.snapshot.value['missed_order_counter']}');
showOverlay(
context: context,
awaitCount: awaitCount,
completeCount: completeCount,
todaysCount: todaysCount,
missedCount: missedCount,
);
return Column(
children: <Widget>[
Container(
key: _todaysButtonKey,
width: deviceWidth * 0.7,
child: FlatButton(
onPressed: () {
removeOverlays(); // Remove overlays and navigate
Navigator.of(context).pushNamed(
'/todays-orders-screen',
arguments: <String>[officeName, locationCoords],
);
},
color: Colors.blue,
child: Text(
'Today\'s Orders',
style: TextStyle(
color: Colors.white,
fontSize: 18.0,
fontWeight: FontWeight.bold,
),
),
),
),
SizedBox(height: 30),
Container(
key: _awatingButtonKey,
width: deviceWidth * 0.7,
child: FlatButton(
onPressed: () async {
removeOverlays();
await firebaseAdminRef
.child('Office Location')
.child(officeName)
.update({'awaiting_order_counter': 0});
Navigator.of(context).pushNamed(
'/awaiting-orders-screen',
arguments: <String>[officeName, locationCoords],
);
},
color: Colors.blue,
child: Text(
'Awaiting Orders',
style: TextStyle(
color: Colors.white,
fontSize: 18.0,
fontWeight: FontWeight.bold,
),
),
),
),
Container(
width: deviceWidth * 0.7,
child: FlatButton(
onPressed: () {
removeOverlays();
Navigator.of(context).pushNamed(
'/confirmed-orders-screen',
arguments: <String>[officeName, locationCoords],
);
},
color: Colors.blue,
child: Text(
'Confirmed Orders',
style: TextStyle(
color: Colors.white,
fontSize: 18.0,
fontWeight: FontWeight.bold,
),
),
),
),
Container(
width: deviceWidth * 0.7,
child: FlatButton(
onPressed: () {
removeOverlays();
Navigator.of(context).pushNamed(
'/cancelled-orders-screen',
arguments: <String>[officeName, locationCoords],
);
},
color: Colors.blue,
child: Text(
'Cancelled Orders',
style: TextStyle(
color: Colors.white,
fontSize: 18.0,
fontWeight: FontWeight.bold,
),
),
),
),
Container(
key: _completedButtonKey,
width: deviceWidth * 0.7,
child: FlatButton(
onPressed: () async {
removeOverlays();
await firebaseAdminRef
.child('Office Location')
.child(officeName)
.update({'completed_order_counter': 0});
Navigator.of(context).pushNamed(
'/completed-orders-screen',
arguments: <String>[officeName, locationCoords],
);
},
color: Colors.blue,
child: Text(
'Completed Orders',
style: TextStyle(
color: Colors.white,
fontSize: 18.0,
fontWeight: FontWeight.bold,
),
),
),
),
Container(
key: _missedButtonKey,
width: deviceWidth * 0.7,
child: FlatButton(
onPressed: () async {
await firebaseAdminRef
.child('Office Location')
.child(officeName)
.update({'missed_order_counter': 0});
Navigator.of(context).pushNamed(
'/missed-orders-screen',
arguments: <String>[officeName, locationCoords],
);
},
color: Colors.blue,
child: Text(
'Missed Orders',
style: TextStyle(
color: Colors.white,
fontSize: 18.0,
fontWeight: FontWeight.bold,
),
),
),
),
],
);
} else if (snapshot.hasError) {
return Text(snapshot.error.toString());
}
return Center(child: CircularProgressIndicator());
},
),
Container(
width: deviceWidth * 0.7,
child: FlatButton(
onPressed: () {
overlayAwaitingEntry.remove();
overlayCompletedEntry.remove();
Navigator.of(context).push(
MaterialPageRoute(
builder: (BuildContext context) => OrderMap(
latitude: double.tryParse(
'${locationCoords.split(' ')[0]}'),
longitude: double.tryParse(
'${locationCoords.split(' ')[1]}'),
shouldShowAllDeliveryBoys: true,
),
),
);
},
color: Colors.blue,
child: Text(
'Delivery Boys',
style: TextStyle(
color: Colors.white,
fontSize: 18.0,
fontWeight: FontWeight.bold,
),
),
),
),
StreamBuilder<Event>(
stream: firebaseAdminRef
.child('Office Location')
.child(officeName)
.child('total_orders')
.onValue,
builder: (BuildContext context, AsyncSnapshot<Event> snapshot) {
if (snapshot.hasData) {
return Align(
alignment: Alignment.centerRight,
child: Container(
margin: const EdgeInsets.symmetric(
horizontal: 12.0,
vertical: 12.0,
),
child: Text(
'Total Orders = ${snapshot?.data?.snapshot?.value ?? 0}',
style: TextStyle(
color: Colors.black,
fontSize: 18.0,
),
),
),
);
} else if (snapshot.hasError) {
return Text(snapshot.error.toString());
}
return Center(child: CircularProgressIndicator());
},
)
],
),
),
),
);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment