Graphs properly rendered and fetched

This commit is contained in:
Felix 2019-08-16 16:44:24 +01:00
parent 94150ddd76
commit fdb6a5c69b
2 changed files with 182 additions and 55 deletions

View file

@ -5,25 +5,34 @@ import 'package:shared_preferences/shared_preferences.dart';
import 'package:charts_flutter/flutter.dart' as charts; import 'package:charts_flutter/flutter.dart' as charts;
class GraphData { class GraphData {
List<charts.Series> data = new List<charts.Series>(); var chartType;
List<charts.Series<dynamic, DateTime>> graph;
Future<List<charts.Series<dynamic, DateTime>>> getGraphData(String graphType) async { GraphData(
// print("called"); this.chartType,
/// Graph types: );
/// - total_last_week
/// - avg_spend_last_week List<TimeSeriesSpend> cachedData;
/// - total_last_month bool loaded = false;
/// - avg_spend_last_month
/// Future<void> setGraphData() async {
/// HTTP POST request sample: if (loaded == true) {
/// {"graph":"total_last_week","session_key":"blahblahblah"} this.graph = [
new charts.Series<TimeSeriesSpend, DateTime>(
id: 'Spend',
colorFn: (_, __) => charts.MaterialPalette.blue.shadeDefault,
domainFn: (TimeSeriesSpend spend, _) => spend.time,
measureFn: (TimeSeriesSpend spend, _) => spend.spend,
data: cachedData,
)
];
}
charts.Series<dynamic, DateTime> dataSeries = new charts.Series<dynamic, DateTime>();
final url = "https://dev.peartrade.org/api/v1/customer/graphs"; final url = "https://dev.peartrade.org/api/v1/customer/graphs";
SharedPreferences preferences = await SharedPreferences.getInstance(); SharedPreferences preferences = await SharedPreferences.getInstance();
Map<String, String> body = { Map<String, String> body = {
'graph': graphType, 'graph': this.chartType,
'session_key': preferences.get('LastToken'), 'session_key': preferences.get('LastToken'),
}; };
@ -37,29 +46,82 @@ class GraphData {
final List<dynamic> labels = responseJson['graph']['labels']; final List<dynamic> labels = responseJson['graph']['labels'];
final List<dynamic> data = responseJson['graph']['data']; final List<dynamic> data = responseJson['graph']['data'];
for (int i = 0; i < data.length; i++) { List<TimeSeriesSpend> timeSeriesSpendList = new List<TimeSeriesSpend>();
// print(labels[i].toString() + " : " + data[i].toString());
}
// final List<String> bounds = responseJson['graph']['bounds']; // why is this even returned?
/* for (int i = 0; i < labels.length; i++) {
final data = [ timeSeriesSpendList.add(new TimeSeriesSpend(data[i]*1.00, DateTime.parse(labels[i])));
new TimeSeriesSales(new DateTime(2017, 9, 19), 5), // print(timeSeriesSpendList[i].time.toString() + " : " + timeSeriesSpendList[i].spend.toString());
new TimeSeriesSales(new DateTime(2017, 9, 26), 25), }
new TimeSeriesSales(new DateTime(2017, 10, 3), 100),
new TimeSeriesSales(new DateTime(2017, 10, 10), 75), cachedData = timeSeriesSpendList;
loaded = true;
this.graph = [
new charts.Series<TimeSeriesSpend, DateTime>(
id: 'Spend',
colorFn: (_, __) => charts.MaterialPalette.blue.shadeDefault,
domainFn: (TimeSeriesSpend spend, _) => spend.time,
measureFn: (TimeSeriesSpend spend, _) => spend.spend,
data: timeSeriesSpendList,
)
]; ];
*/ } else {
final errorMessage = json.decode(response.body)['message'];
print("Error: " + errorMessage);
this.graph = null;
}
}
Future<List<charts.Series<dynamic, DateTime>>> getGraphData() async {
if (loaded == true) {
return [
new charts.Series<TimeSeriesSpend, DateTime>(
id: 'Spend',
colorFn: (_, __) => charts.MaterialPalette.blue.shadeDefault,
domainFn: (TimeSeriesSpend spend, _) => spend.time,
measureFn: (TimeSeriesSpend spend, _) => spend.spend,
data: cachedData,
)
];
}
/// Graph types:
/// - total_last_week
/// - avg_spend_last_week
/// - total_last_month
/// - avg_spend_last_month
///
/// HTTP POST request sample:
/// {"graph":"total_last_week","session_key":"blahblahblah"}
final url = "https://dev.peartrade.org/api/v1/customer/graphs";
SharedPreferences preferences = await SharedPreferences.getInstance();
Map<String, String> body = {
'graph': this.chartType,
'session_key': preferences.get('LastToken'),
};
final response = await http.post(
url,
body: json.encode(body),
);
if (response.statusCode == 200) {
final responseJson = jsonDecode(response.body);
final List<dynamic> labels = responseJson['graph']['labels'];
final List<dynamic> data = responseJson['graph']['data'];
List<TimeSeriesSpend> timeSeriesSpendList = new List<TimeSeriesSpend>(); List<TimeSeriesSpend> timeSeriesSpendList = new List<TimeSeriesSpend>();
for (int i = 0; i < labels.length; i++) { for (int i = 0; i < labels.length; i++) {
// print(DateTime.parse(labels[i])); timeSeriesSpendList.add(new TimeSeriesSpend(data[i]*1.00, DateTime.parse(labels[i])));
timeSeriesSpendList.add(new TimeSeriesSpend(i, DateTime(i))); // print(timeSeriesSpendList[i].time.toString() + " : " + timeSeriesSpendList[i].spend.toString());
// timeSeriesSpendList.add(new TimeSeriesSpend(data[i], DateTime.parse(labels[i])));
} }
// print(timeSeriesSpendList); cachedData = timeSeriesSpendList;
loaded = true;
return [ return [
new charts.Series<TimeSeriesSpend, DateTime>( new charts.Series<TimeSeriesSpend, DateTime>(
@ -70,18 +132,6 @@ class GraphData {
data: timeSeriesSpendList, data: timeSeriesSpendList,
) )
]; ];
/*
new charts.Series<TimeSeriesSales, DateTime>(
id: 'Sales',
colorFn: (_, __) => charts.MaterialPalette.blue.shadeDefault,
domainFn: (TimeSeriesSales sales, _) => sales.time,
measureFn: (TimeSeriesSales sales, _) => sales.sales,
data: data,
)*/
// print(labels[5]);
// print(data[5]);
} else { } else {
final errorMessage = json.decode(response.body)['message']; final errorMessage = json.decode(response.body)['message'];
print("Error: " + errorMessage); print("Error: " + errorMessage);
@ -95,7 +145,7 @@ class GraphData {
class TimeSeriesSpend { class TimeSeriesSpend {
final DateTime time; final DateTime time;
final int spend; final double spend;
TimeSeriesSpend(this.spend, this.time); TimeSeriesSpend(this.spend, this.time);
} }

View file

@ -29,8 +29,16 @@ class StatsPage extends StatefulWidget {
class StatsPageState extends State<StatsPage> { class StatsPageState extends State<StatsPage> {
GraphData graphData = new GraphData(); /// Graph types:
List<charts.Series<dynamic, DateTime>> displayedGraphData; /// - total_last_week
/// - avg_spend_last_week
/// - total_last_month
/// - avg_spend_last_month
GraphData totalLastWeekGraph = new GraphData("total_last_week");
GraphData avgSpendLastWeekGraph = new GraphData("avg_spend_last_week");
GraphData totalLastMonthGraph = new GraphData("total_last_month");
GraphData avgSpendLastMonth = new GraphData("avg_spend_last_month");
@override @override
void initState() { void initState() {
@ -50,12 +58,29 @@ class StatsPageState extends State<StatsPage> {
@override @override
Widget build(BuildContext context) { Widget build(BuildContext context) {
if (graphData.data.length == 0) {
graphData.getGraphData('total_last_week').then((fetchedData) { // Initializing graphs:
displayedGraphData = (fetchedData);
for (int i = 0; i < fetchedData[0].data.length; i++) { if (!totalLastWeekGraph.loaded) {
print(fetchedData[0].data[i].time); // this is getting very frustrating totalLastWeekGraph.setGraphData().then((_) {
} setState(() {});
});
}
if (!avgSpendLastWeekGraph.loaded) {
avgSpendLastWeekGraph.setGraphData().then((_) {
setState(() {});
});
}
if (!totalLastMonthGraph.loaded) {
totalLastMonthGraph.setGraphData().then((_) {
setState(() {});
});
}
if (!avgSpendLastMonth.loaded) {
avgSpendLastMonth.setGraphData().then((_) {
setState(() {}); setState(() {});
}); });
} }
@ -84,7 +109,7 @@ class StatsPageState extends State<StatsPage> {
Container( Container(
padding: EdgeInsets.fromLTRB(0.0,17,0.0,0.0), padding: EdgeInsets.fromLTRB(0.0,17,0.0,0.0),
child : Text( child : Text(
"This Week's Spend", "Last Week's Total Spend",
textAlign: TextAlign.center, textAlign: TextAlign.center,
style: TextStyle( style: TextStyle(
fontSize: 22.0, fontSize: 22.0,
@ -97,12 +122,64 @@ class StatsPageState extends State<StatsPage> {
Container( Container(
padding: EdgeInsets.symmetric(horizontal: 10), padding: EdgeInsets.symmetric(horizontal: 10),
height: 200, height: 200,
// width: 250, child: totalLastWeekGraph.graph != null ? new charts.TimeSeriesChart(totalLastWeekGraph.graph) : Container(), //List<Series<dynamic, DateTime>>
),
// child: new TimeSeries(), Container(
child: displayedGraphData != null ? new charts.TimeSeriesChart(displayedGraphData) : Container(), //List<Series<dynamic, DateTime>> padding: EdgeInsets.fromLTRB(0.0,17,0.0,0.0),
// child: new charts.TimeSeriesChart(displayedGraphData), child : Text(
// child: new SimpleTimeSeriesChart(),//seriesList: List<charts.Series> "Last Week's Average Spend",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 22.0,
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
),
Container(
padding: EdgeInsets.symmetric(horizontal: 10),
height: 200,
child: avgSpendLastWeekGraph.graph != null ? new charts.TimeSeriesChart(avgSpendLastWeekGraph.graph) : Container(), //List<Series<dynamic, DateTime>>
),
Container(
padding: EdgeInsets.fromLTRB(0.0,17,0.0,0.0),
child : Text(
"Last Month's Spend",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 22.0,
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
),
Container(
padding: EdgeInsets.symmetric(horizontal: 10),
height: 200,
child: totalLastMonthGraph.graph != null ? new charts.TimeSeriesChart(totalLastMonthGraph.graph) : Container(), //List<Series<dynamic, DateTime>>
),
Container(
padding: EdgeInsets.fromLTRB(0.0,17,0.0,0.0),
child : Text(
"Last Month's Average Spend",
textAlign: TextAlign.center,
style: TextStyle(
fontSize: 22.0,
color: Colors.black,
fontWeight: FontWeight.bold,
),
),
),
Container(
padding: EdgeInsets.symmetric(horizontal: 10),
height: 200,
child: avgSpendLastMonth.graph != null ? new charts.TimeSeriesChart(avgSpendLastMonth.graph) : Container(), //List<Series<dynamic, DateTime>>
), ),
], ],