Skip to content

Instantly share code, notes, and snippets.

@zeeshan-mehdi
Created June 1, 2021 15:56
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save zeeshan-mehdi/a2138b5564519f1a8f2229832fa6320a to your computer and use it in GitHub Desktop.
Save zeeshan-mehdi/a2138b5564519f1a8f2229832fa6320a to your computer and use it in GitHub Desktop.
city operator code
import 'dart:convert';
import 'package:dropdownfield/dropdownfield.dart';
import 'package:fl_chart/fl_chart.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter/widgets.dart';
import 'package:searchable_dropdown/searchable_dropdown.dart';
import 'package:transit/Login.dart';
import 'package:http/http.dart' as http;
import 'package:shared_preferences/shared_preferences.dart';
import 'package:transit/Performance/mainpage.dart';
import 'package:transit/Performance/pichartCityOperator.dart';
import 'package:toast/toast.dart';
import '../global.dart';
class CityOperator extends StatefulWidget {
@override
CityOperatorState createState() => CityOperatorState();
}
class CityOperatorState extends State<CityOperator> {
var jsondata;
String _city;
String _cityOperator;
String to;
String from;
var graphsresult;
String token;
TextEditingController _textEditingControllerFromDate =
new TextEditingController();
TextEditingController _textEditingControllerToDate =
new TextEditingController();
String endDay;
//List dataforcities = List();
// List dataforOperators = List();
String cityid;
String operatorid;
String id;
bool isvisible1forchart = false;
bool isvisibleforselect = true;
bool isvisiblefornoresults = true;
bool isvisibleforexpanded = false;
List dataforOperators = List();
List<DropdownMenuItem> dataforOperatorsitems = [];
String selectedOperator;
// String selectedCity;
List dataforcities = List();
List<DropdownMenuItem> items = [];
String selectedCity;
// String selectedJournry;
var onTime;
var late;
var early;
bool isLoading = false;
bool isResetOperatorDropDown = false;
List<PieChartSectionData> _section = List<PieChartSectionData>();
Future<String> getdataforcity() async {
setState(() {
isLoading = true;
});
SharedPreferences sharedPrefrences = await SharedPreferences.getInstance();
token = sharedPrefrences.getString('token');
print("object");
Map<String, String> headers = {
'Content-Type': 'application/json',
"Authorization": "Bearer $token",
};
Uri APIURL = Uri.parse("https://portal.mytransitguru.com/api/cities");
Map mapdata = {};
print("json Data :$mapdata");
http.Response response = await http.get(
APIURL,
headers: headers,
);
var jsondata = null;
print(response.statusCode);
if (response.statusCode == 200) {
jsondata = json.decode(response.body);
setState(() {
isLoading = false;
});
// id = jsondata[0]['id'];
print(jsondata.length);
if(jsondata.length == 0){
Toast.show("No data found", context,
duration: Toast.LENGTH_LONG, gravity: Toast.BOTTOM);
}else{
print("nothings");
}
// items.add(DropdownMenuItem(
// child: Text("abc"),
// value: "cds",
// ));
setState(() {
dataforcities = jsondata;
});
print(jsondata);
print("${dataforcities.map((e) => e).toString()}");
var aa = dataforcities.map((e) => e).toList();
for (var item in aa){
print(item);
items.add(DropdownMenuItem(
child: Text("${item['name'].toString()}."),
value: "${item['name'].toString()}",
));
}
print('yes good');
} else if (response.statusCode == 203) {
setState(() {
isLoading = false;
});
Toast.show("StatusCode is ${response.statusCode} Something Missing in Request", context,
duration: Toast.LENGTH_LONG, gravity: Toast.BOTTOM);
} else {
setState(() {
isLoading = false;
});
Toast.show("StatusCode is ${response.statusCode} Something Missing in Request", context,
duration: Toast.LENGTH_LONG, gravity: Toast.BOTTOM);
print('no no no ');
}
}
@override
void initState() {
super.initState();
generateData(null, null, null);
getdataforcity();
}
Future<String> getDataForOperators() async {
print("object");
setState(() {
isResetOperatorDropDown = true;
isLoading = true;
});
Map<String, String> headers = {
'Content-Type': 'application/json',
"Authorization": "Bearer $token",
};
print(cityid);
Uri APIURL =
Uri.parse("https://portal.mytransitguru.com/api/cities/$cityid/operators");
Map mapdata = {};
print("json Data :$mapdata");
http.Response response = await http.get(
APIURL,
headers: headers,
);
var jsondata = null;
print(response.statusCode);
if (response.statusCode == 200) {
jsondata = json.decode(response.body);
print(jsondata);
// setState(() {
// isLoading = false;
// });
print(jsondata.length);
setState(() {
selectedOperator = "";
dataforOperatorsitems = [];
dataforOperators = jsondata;
});
if(dataforOperators.length == 0){
Toast.show("No data found", context,
duration: Toast.LENGTH_LONG, gravity: Toast.BOTTOM);
}else{
var aa = dataforOperators.map((e) => e).toList();
for (var item in aa){
print(item);
dataforOperatorsitems.add(DropdownMenuItem(
child: Text("${item['name'].toString()}."),
value: "${item['name'].toString()}",
));
}
}
setState(() {
isLoading = false;
});
print("this " + dataforOperators.toString());
print('yes good');
} else if (response.statusCode == 203) {
setState(() {
isLoading = false;
// isOperatorDataLoad = false;
});
Toast.show("StatusCode is ${response.statusCode} Something Missing in Request", context,
duration: Toast.LENGTH_LONG, gravity: Toast.BOTTOM);
} else {
setState(() {
isLoading = false;
});
Toast.show("StatusCode is ${response.statusCode} Something Missing in Request", context,
duration: Toast.LENGTH_LONG, gravity: Toast.BOTTOM);
print('no no no ');
}
setState(() {
isResetOperatorDropDown = false;
});
}
// List<DropdownMenuItem> items = [];
@override
Widget build(BuildContext context) {
MediaQueryData _mediaQueryData;
_mediaQueryData = MediaQuery.of(context);
double width = _mediaQueryData.size.width;
double height = _mediaQueryData.size.height;
return SafeArea(
child: Scaffold(
backgroundColor: Color(0xFFFDFDFD),
body: Stack(
children: [
SingleChildScrollView(
child: Column(children: [
Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
border: Border.all(color: Colors.white30),
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.1),
spreadRadius: 0,
blurRadius: 7,
offset: Offset(0, .01), // changes position of shadow
),
]),
width: width,
height: height / 8,
child: Column(
children: [
SizedBox(
height: 30,
),
Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Padding(
padding: const EdgeInsets.only(left: 15.0),
child: Text(
"PEROFORMANCE",
style: TextStyle(
fontSize: 12,
letterSpacing: 1.5,
color: Color(0xFFFC6011),
fontWeight: FontWeight.w600),
),
),
Padding(
padding: const EdgeInsets.only(right: 15.0),
child: GestureDetector(
onTap: () {
Navigator.of(context).push(MaterialPageRoute(
builder: (context) => Mainpage(currentPage : 1)));
},
child: Text(
"Back",
style: TextStyle(
fontSize: 12,
color: Colors.black,
fontWeight: FontWeight.normal),
),
),
),
],
),
SizedBox(
height: 5,
),
Align(
alignment: Alignment.centerLeft,
child: Padding(
padding: const EdgeInsets.only(left: 15.0),
child: Text(
"City Operator",
style: TextStyle(
fontSize: 27, fontWeight: FontWeight.bold),
),
),
),
],
),
),
SizedBox(
height: height / 25,
),
Container(
child: Column(
children: [
Visibility(
visible: isvisibleforselect,
child: Center(
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
border: Border.all(color: Colors.white30),
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.1),
spreadRadius: 0,
blurRadius: 7,
offset: Offset(
0, .01), // changes position of shadow
),
]),
width: width * .9,
child: Column(
children: [
Center(
child: Container(
width: width * 1,
child: Padding(
padding: const EdgeInsets.only(left: 0.0),
child: InkWell(
onTap: () async {
// DropdownMenuItem(value: ,)
},
child: Container(
//height: 70,
// width: Responsive.width(100, context),
color: Colors.white,
child : SearchableDropdown.single(
items: items,
value: selectedCity,
hint: Padding(
padding: const EdgeInsets.only(top:15.0, bottom: 15.0),
child: Text("Select City"),
),
searchHint: "Select City",
onChanged: (value) {
setState(() {
cityid = dataforcities.where((i) => i['name'].toString() == value).first['id'];
print(value);
print(cityid);
selectedCity = value;
});
getDataForOperators();
},
isExpanded: true,
),
),
),
),
),
),
Center(
child: Container(
width: width * 1,
child: isResetOperatorDropDown ? defaultDropdwon("Operator") : Container(
//height: 70,
// width: Responsive.width(100, context),
color: Colors.white,
child : SearchableDropdown.single(
items: dataforOperatorsitems,
value: selectedOperator,
hint: Padding(
padding: const EdgeInsets.only(top:15.0, bottom: 15.0,),
child: Text("Select Operator"),
),
searchHint: "Select Operator",
onChanged: (value) {
setState(() {
operatorid = dataforOperators.where((i) => i['name'].toString() == value).first['id'];
print(value);
print(operatorid);
selectedOperator = value;
});
},
isExpanded: true,
),
),
),
),
Padding(
padding: const EdgeInsets.only(left: 8.0,top: 8),
child: TextFormField(
controller: _textEditingControllerFromDate,
readOnly: true,
decoration: InputDecoration(
hintText: " From",
suffixIcon: IconButton(
onPressed: () => print(DatepickerFrom(
context,
_textEditingControllerFromDate)),
icon: new Image.asset("images/CalenderIcon.png"),
),
),
),
),
Padding(
padding: const EdgeInsets.only(left: 8.0,top: 8),
child: TextFormField(
controller: _textEditingControllerToDate,
readOnly: true,
decoration: InputDecoration(
hintText: " To",
suffixIcon: IconButton(
onPressed: () => print(DatepickerTo(
context, _textEditingControllerToDate)),
icon: new Image.asset("images/CalenderIcon.png"),
),
),
),
),
SizedBox(
height: height / 55,
),
Align(
alignment: Alignment.centerRight,
child: Padding(
padding: const EdgeInsets.only(right: 8.0),
child: TextButton(
child: Padding(
padding: const EdgeInsets.fromLTRB(
15.0, 0, 15, 0),
child: Text("Generate",
style: TextStyle(color: Colors.white, fontSize: 18),
),
),
onPressed: () async {
chartCityOperator();
// Navigator.push(
// context,
// MaterialPageRoute(
// builder: (context) =>
// ChartforCityOperator(
// jsondata: graphsresult,
// )));
setState(() {
isvisible1forchart = true;
isvisibleforselect = false;
isvisiblefornoresults = false;
isvisibleforexpanded = true;
});
},
style: ButtonStyle(
backgroundColor:
MaterialStateProperty.all<Color>(
Colors.deepOrangeAccent),
foregroundColor:
MaterialStateProperty.all<Color>(
Colors.white),
),
// style,: RoundedRectangleBorder(
// borderRadius: new BorderRadius.circular(10.0)
// )
),
),
)
],
),
),
),
),
SizedBox(height: height / 100),
Visibility(
visible: isvisiblefornoresults,
child: Center(
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
border: Border.all(color: Colors.white30),
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.1),
spreadRadius: 0,
blurRadius: 7,
offset: Offset(
0, .01), // changes position of shadow
),
]),
child: Align(
alignment: Alignment.center,
child: Text(
"No Results Found",
style: TextStyle(color: Colors.grey, fontSize: 22),
),
),
width: width * .9,
height: height / 2,
),
),
),
Visibility(
visible: isvisibleforexpanded,
child: Container(
child: Container(
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(10),
border: Border.all(color: Colors.white30),
color: Colors.white,
boxShadow: [
BoxShadow(
color: Colors.grey.withOpacity(0.5),
spreadRadius: 2,
blurRadius: 7,
offset:
Offset(0, 3), // changes position of shadow
),
]),
width: width * .9,
height: height / 12,
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Padding(
padding: const EdgeInsets.only(left: 15.0),
child: Text(
"City Operator Form",
style: TextStyle(fontSize: 17),
),
),
Padding(
padding: const EdgeInsets.only(right: 15.0),
child: InkWell(
child: Image.asset(
'images/expanded.png',
),
onTap: () {
setState(() {
isvisible1forchart = true;
isvisibleforselect = true;
isvisiblefornoresults = false;
isvisibleforexpanded = false;
});
},
),
),
],
),
),
),
),
SizedBox(
height: 10,
),
Visibility(
visible: isvisible1forchart,
child: Column(
children: [
//till here
Container(
child: AspectRatio(
aspectRatio: 1,
child: FlChart(
chart: PieChart(PieChartData(
// pieTouchData: PieTouchData(touchCallback: (pieTouchResponse) {
// setState(() {
// final desiredTouch = pieTouchResponse.touchInput is! PointerExitEvent &&
// pieTouchResponse.touchInput is! PointerUpEvent;
// if (desiredTouch && pieTouchResponse.touchedSection != null) {
// touchedIndex = pieTouchResponse.touchedSection.touchedSectionIndex;
// } else {
// touchedIndex = -1;
// }
// });
// }),
startDegreeOffset: 180,
borderData: FlBorderData(
show: false,
),
sectionsSpace: 8,
centerSpaceRadius: 0,
sections: _section)),
),
),
width: 400,
height: 400,
),
Divider(
color: Colors.black12,
height: 0.5,
endIndent: 16,
indent: 16,
),
SizedBox(
height: 8,
),
Center(
child: Padding(
padding: const EdgeInsets.fromLTRB(15, 15, 30, 0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
Text("Early"),
Text("On-time"),
Text("Late"),
],
),
),
),
Padding(
padding: const EdgeInsets.fromLTRB(15, 15, 15, 0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
children: [
RichText(
text: TextSpan(
text:jsondata!=null? 0.0.k_m_b_generator(jsondata['early']) ?? "Loading" : "Loading",
style: TextStyle(
color: Colors.black,
fontSize: 22,
fontWeight: FontWeight.bold),
children: <TextSpan>[
TextSpan(
text:early!=null? double.parse(early.toString()).isNaN ? "${early.toString() == "NaN" ? " " +"0%" :" " +"${early.toString()}"}" : " "+" ${early.toString()}%": " "+ "0%",
style: TextStyle(
color: Colors.deepOrangeAccent,
fontSize: 16))
])),
RichText(
text: TextSpan(
text:jsondata!=null? 0.0.k_m_b_generator(jsondata['onTime']) ?? "Loading": "Loading",
style: TextStyle(
color: Colors.black,
fontSize: 22,
fontWeight: FontWeight.bold),
children: <TextSpan>[
TextSpan(
text:onTime!=null? double.parse(onTime.toString()).isNaN ? "${onTime.toString() == "NaN" ? " " +"0%" :" " +"${onTime.toString()}"}" : " "+" ${onTime.toString()}%": " "+ "0%",
style: TextStyle(
color: Colors.deepOrangeAccent,
fontSize: 16))
])),
RichText(
text: TextSpan(
text: jsondata!=null? 0.0.k_m_b_generator(jsondata['late'])?? "Loading": "Loading",
style: TextStyle(
color: Colors.black,
fontSize: 22,
fontWeight: FontWeight.bold),
children: <TextSpan>[
TextSpan(
text:late!=null? double.parse(late.toString()).isNaN ? "${late.toString() == "NaN" ? " " +"0%" :" " +"${late.toString()}"}" : " "+" ${late.toString()}%": " "+ "0%",
style: TextStyle(
color: Colors.deepOrangeAccent,
fontSize: 16))
])),
],
),
),
SizedBox(
height: 15,
),
Padding(
padding: const EdgeInsets.fromLTRB(15, 15, 30, 0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text("Avg Early (Mm:Ss) "),
Text("Avg Late (Mm:Ss) "),
],
),
),
Padding(
padding: const EdgeInsets.fromLTRB(15, 15, 30, 30),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: [
Text(
jsondata == null
? "Loading"
: jsondata['avgEarlyTime'].toString(),
style: TextStyle(
fontSize: 20, fontWeight: FontWeight.bold),
),
Text(
jsondata == null
? "Loading"
: jsondata['avgLateTime'].toString(),
style: TextStyle(
fontSize: 20,
fontWeight: FontWeight.bold)),
],
),
),
],
),
),
],
),
),
]),
),
isLoading ? Positioned(
top: MediaQuery.of(context).size.height/2-100,
left: MediaQuery.of(context).size.width/2-20,
child: spinkit):Container()
],
),
),
);
}
generatePieChartWidgets(){
}
Future chartCityOperator() async {
setState(() {
isLoading = true;
});
Uri APIURL = Uri.parse(
"https://portal.mytransitguru.com/api/performance/city-operator");
final mapdata = {
"cityId": cityid,
"operatorId": operatorid,
"startDate": from,
"endDate": to
};
Map<String, String> headers = {
'Content-Type': 'application/json',
"Authorization": "Bearer $token",
};
print("json Data :$mapdata");
http.Response response =
await http.post(APIURL, headers: headers, body: jsonEncode(mapdata));
// var data = jsonDecode(response.body);
// print("Data :$data");
if (response.statusCode == 200) {
jsondata = json.decode(response.body);
early =double.parse( (jsondata['early']/(jsondata['early']+jsondata['onTime']+jsondata['late'])*100).toStringAsFixed(2));
onTime = double.parse( (jsondata['onTime']/(jsondata['early']+jsondata['onTime']+jsondata['late'])*100).toStringAsFixed(2));
late = double.parse( (jsondata['late']/(jsondata['early']+jsondata['onTime']+jsondata['late'])*100).toStringAsFixed(2));
generateData( jsondata['early'].toDouble(), jsondata['late'].toDouble(),jsondata['onTime'].toDouble());
print('yes good');
print(jsondata);
graphsresult = jsondata;
print("this" + graphsresult.toString());
if(graphsresult == []){
Toast.show("No data found", context,
duration: Toast.LENGTH_LONG, gravity: Toast.BOTTOM);
}else{
}
setState(() {
isLoading = false;
});
} else if (response.statusCode == 406) {
setState(() {
isLoading = false;
});
Toast.show("StatusCode is ${response.statusCode} Something Missing in Request", context,
duration: Toast.LENGTH_LONG, gravity: Toast.BOTTOM);
print("Issue");
} else {
print('no no no ');
Toast.show("StatusCode is ${response.statusCode} Something Missing in Request", context,
duration: Toast.LENGTH_LONG, gravity: Toast.BOTTOM);
setState(() {
isLoading = false;
});
}
}
generateData(early,late,onTime){
print(early is int);
print(late is int);
print(onTime is int);
PieChartSectionData _item1 = PieChartSectionData(
color: Colors.red,
title: "Late",
value: late??30,
radius: 120,
titleStyle: TextStyle(color: Colors.white, fontSize: 15));
PieChartSectionData _item2 = PieChartSectionData(
color: Colors.blue,
title: "Early",
value: early?? 40,
radius: 120,
titleStyle: TextStyle(color: Colors.white, fontSize: 15));
PieChartSectionData _item3 = PieChartSectionData(
color: Colors.green,
title: "On-time",
value:onTime?? 30,
radius: 120,
titleStyle: TextStyle(color: Colors.white, fontSize: 15));
_section = [_item1, _item2, _item3];
}
Future<void> DatepickerTo(context, TextEditingController controller) async {
DateTime selectedDate = DateTime.now();
final DateTime picked = await showDatePicker(
context: context,
initialDate: selectedDate,
firstDate: DateTime(2015, 8),
lastDate: DateTime(2101));
if (picked != null && picked != selectedDate)
setState(() {
selectedDate = picked;
to = selectedDate.toString();
});
controller.text = "${selectedDate.toLocal()}".split(' ')[0];
print(selectedDate);
}
Future<void> DatepickerFrom(context, TextEditingController controller) async {
DateTime selectedDate = DateTime.now();
final DateTime picked = await showDatePicker(
context: context,
initialDate: selectedDate,
firstDate: DateTime(2015, 8),
lastDate: DateTime(2101));
if (picked != null && picked != selectedDate)
setState(() {
selectedDate = picked;
from = selectedDate.toString();
});
controller.text = "${selectedDate.toLocal()}".split(' ')[0];
print(selectedDate);
}
}
extension ExtendedDouble on double {
String get toPercentString{
" "+ this.toString()+"%";
}
String k_m_b_generator(num) {
if (num > 999 && num < 99999) {
return "${(num / 1000).toStringAsFixed(1)}K";
} else if (num > 99999 && num < 999999) {
return "${(num / 1000).toStringAsFixed(0)}K";
} else if (num > 999999 && num < 999999999) {
return "${(num / 1000000).toStringAsFixed(1)}M";
} else if (num > 999999999) {
return "${(num / 1000000000).toStringAsFixed(1)}B";
} else {
return num.toString();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment