Related
I am trying to add legend to SfCartesianChart. I am getting "Null check operator used on a null value" error. You can see the code below.
class AllInLineChart extends StatefulWidget {
#override
State<AllInLineChart> createState() => _AllInLineChartState();
final Data chartData;
const AllInLineChart(this.chartData);
}
class _AllInLineChartState extends State<AllInLineChart> {
#override
Widget build(BuildContext context) {
final Data _chart = widget.chartData;
return Container(
margin: margin10,
decoration: boxDecoration,
child: SfCartesianChart(
legend: Legend(isVisible: true),
primaryXAxis: DateTimeAxis(),
primaryYAxis: NumericAxis(),
series: <ChartSeries>[
SplineSeries<dataItem, DateTime>(
name: 'Crypto',
dataSource: _chart.cryptoItems,
xValueMapper: (dataItem data, _) => data.time,
yValueMapper: (dataItem data, _) => data.totalAmountInTime,
markerSettings: MarkerSettings(isVisible: true),
),
SplineSeries<dataItem, DateTime>(
name: 'Stock',
dataSource: _chart.stockItems,
xValueMapper: (dataItem data, _) => data.time,
yValueMapper: (dataItem data, _) => data.totalAmountInTime,
markerSettings: MarkerSettings(isVisible: true),
),
SplineSeries<dataItem, DateTime>(
dataSource: _chart.etfItems,
xValueMapper: (dataItem data, _) => data.time,
yValueMapper: (dataItem data, _) => data.totalAmountInTime,
name: 'ETF',
markerSettings: MarkerSettings(isVisible: true),
),
SplineSeries<dataItem, DateTime>(
dataSource: _chart.currencyItems,
xValueMapper: (dataItem data, _) => data.time,
yValueMapper: (dataItem data, _) => data.totalAmountInTime,
name: 'Currency',
markerSettings: MarkerSettings(isVisible: true),
),
SplineSeries<dataItem, DateTime>(
dataSource: _chart.cashItems,
xValueMapper: (dataItem data, _) => data.time,
yValueMapper: (dataItem data, _) => data.totalAmountInTime,
name: 'Cash',
markerSettings: MarkerSettings(isVisible: true),
),
],
),
);
}
}
You can see error here
If I remove legend: Legend(isVisible: true), from code, it is working without error. But I need legend. Thanks for your help.
You can see working version here
My sample data is:
class dataItem {
final DateTime time;
final double totalAmountInTime;
dataItem(this.time, this.totalAmountInTime);
}
class Data with ChangeNotifier {
final List<dataItem> _cryptoItems = [
dataItem(DateTime.parse("20220820"), 10000),
dataItem(DateTime.parse("20220821"), 5000),
dataItem(DateTime.parse("20220822"), 50000),
dataItem(DateTime.parse("20220823"), 25000),
dataItem(DateTime.parse("20220824"), 100000),
];
List<dataItem> get cryptoItems {
return [..._cryptoItems];
}
final List<dataItem> _stockItems = [
dataItem(DateTime.parse("20220820"), 1000),
dataItem(DateTime.parse("20220821"), 500),
dataItem(DateTime.parse("20220822"), 5000),
dataItem(DateTime.parse("20220823"), 2500),
dataItem(DateTime.parse("20220824"), 10000),
];
List<dataItem> get stockItems {
return [..._stockItems];
}
final List<dataItem> _etfItems = [
dataItem(DateTime.parse("20220820"), 500),
dataItem(DateTime.parse("20220821"), 1000),
dataItem(DateTime.parse("20220822"), 2500),
dataItem(DateTime.parse("20220823"), 5000),
dataItem(DateTime.parse("20220824"), 0),
];
List<dataItem> get etfItems {
return [..._etfItems];
}
final List<dataItem> _currencyItems = [
dataItem(DateTime.parse("20220820"), 5000),
dataItem(DateTime.parse("20220821"), 10000),
dataItem(DateTime.parse("20220822"), 25000),
dataItem(DateTime.parse("20220823"), 50000),
dataItem(DateTime.parse("20220824"), 100000),
];
List<dataItem> get currencyItems {
return [..._currencyItems];
}
final List<dataItem> _cashItems = [
dataItem(DateTime.parse("20220820"), 10000),
dataItem(DateTime.parse("20220821"), 50000),
dataItem(DateTime.parse("20220822"), 25000),
dataItem(DateTime.parse("20220823"), 5000),
dataItem(DateTime.parse("20220824"), 1000),
];
List<dataItem> get cashItems {
return [..._cashItems];
}
}
In the Syncfusion chart, text style of axis label can be initially changed depending on the pointIndex of any of the label?
The code I use has a separate widget on the data label. But I can't change the names in XValueMapper.
To make it clearer, below is an example of a piece of code I use:
SfCartesianChart(
title: ChartTitle(
text: title,
backgroundColor: titleBackColor,
textStyle: titleStyle,
),
selectionGesture: ActivationMode.singleTap,
selectionType: SelectionType.point,
series: <ChartSeries>[
StackedBar100Series<RankingChartData, String>(
dataLabelSettings: DataLabelSettings(
builder: (
data,
point,
series,
pointIndex,
seriesIndex,
) {
if (chartData[pointIndex].name.contains(name!)) {
return Padding(
padding: EdgeInsets.only(right: 150.0.w),
child: Icon(
Icons.check_box,
color: primary.base,
),
);
} else {
return const SizedBox();
}
},
isVisible: true,
),
dataSource: chartData,
selectionBehavior: _selectionBehavior,
xValueMapper: (RankingChartData exp, _) => exp.name,
yValueMapper: (RankingChartData exp, _) => exp.positive,
color: positiveColor ?? Colors.green,
sortingOrder: sort ? SortingOrder.ascending : null,
sortFieldValueMapper:
sort ? (RankingChartData exp, _) => exp.positive : null,
onPointTap: (d) {
showDialog(
context: (context),
builder: (context) {
return AlertDialog(
title: Text(chartData[d.pointIndex!].name),
content: Text.rich(TextSpan(children: [
const TextSpan(text: "Positive\n"),
TextSpan(
text: chartData[d.pointIndex!].positive.toString(),
style: TextStyle(
color: positiveColor ?? Colors.green,
fontSize: 20.sp,
),
),
])),
);
});
}),
],
primaryXAxis: CategoryAxis(),
),
Im trying to create a chart that updates the data by checking every 4 seconds. It checks if the last element of the list is the same as the single element in another list. If not, it will remove the first element and add the newest element in. However this is not updating my graph and it only stays as the initial data. Help please ?
import 'dart:async';
import 'package:flutter/foundation.dart';
import 'package:syncfusion_flutter_charts/charts.dart';
import 'package:flutter/material.dart';
import 'package:http/http.dart' as http;
import 'dart:convert';
import 'globalvar.dart';
import 'home_screen.dart';
import 'chartjsonparse.dart';
class RealHumidityChart extends StatefulWidget {
#override
_RealHumidityChartState createState() => _RealHumidityChartState();
}
class _RealHumidityChartState extends State<RealHumidityChart> {
List<SensorData> chartData = []; // list for storing the last parsed Json data
List<SensorData> singleData = [];
Timer _clearTimer;
Future<String> getChartJsonFromDatabase() async {
// Sending get(url) request using the http client to retrieve the response.
var fullResponse = await http.get(fullUrl);
return fullResponse.body;
}
Future loadSensorData() async {
String jsonString = await getChartJsonFromDatabase(); // Deserialization Step #1
final jsonResponse = json.decode(jsonString); // // Deserialization Step #2
setState(() {
// Mapping the retrieved json response string and adding the sensor data to the chart data list.
for (Map i in jsonResponse) {
chartData.add(
SensorData.fromJson(i) // Deserialization step #3
);
}
});
}
Future loadSingleData() async {
var singleResponse = await http.get(singleUrl);
if (singleResponse.statusCode == 200) {
final singleJsonResponse = json.decode(singleResponse.body);
for (Map i in singleJsonResponse) {
singleData.add(
SensorData.fromJson(i)
);
print("Sucessfully connect singlecode");
print(chartData);
}
}
}
#override
void initState() {
loadSensorData();
_clearTimer = Timer.periodic(Duration(seconds: 4), (Timer t) {
singleData.clear();
loadSingleData();
if (chartData.last != singleData.last){
chartData.removeAt(0);
chartData.add(singleData.last);
setState(() {});
}
});
super.initState();
}
#override
void dispose() {
_clearTimer.cancel();
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Color(0xff264653),
),
body: SfCartesianChart(
margin: EdgeInsets.all(15),
primaryXAxis: CategoryAxis(
title: AxisTitle(
text: "Date",
)
),
primaryYAxis: NumericAxis(
// '%' will be append to all Y-axis labels
labelFormat: '{value} %'
),
//Chart Title
title: (ChartTitle(text: 'Humidity')),
//Enable legend
legend: Legend(isVisible: false),
//Enable tooltip
tooltipBehavior: TooltipBehavior(enable: true),
series: <ChartSeries<SensorData, String>>[
LineSeries<SensorData, String>(
name: 'Humidity Chart',
dataSource: chartData,
xValueMapper: (SensorData data, _) => data.date,
yValueMapper: (SensorData data, _) => data.sen1,
//Enable Label Settings
dataLabelSettings: DataLabelSettings(isVisible: true),
markerSettings: MarkerSettings(isVisible: true),
),
]
),
);
}
}
class SensorData {
SensorData(this.date, this.sen1);
String date;
dynamic sen1;
factory SensorData.fromJson(Map<String, dynamic> parsedJson) {
return SensorData(
parsedJson['Date'].toString(),
parsedJson['Sen1'] as dynamic,
);
}
}
Add SfCartesianChart inSide Future Builder and Update future of FutureBuilder when you want to update like below code.
FutureBuilder(
future: futureDailyCount,
builder: (context, snapshot) {
if (snapshot.hasData) {
return Column(
children: <Widget>[
SfCartesianChart(
plotAreaBorderWidth: 0,
title: ChartTitle(text: 'Daily Progress'),
legend: Legend(
isVisible: isCardView ? false : true,
overflowMode: LegendItemOverflowMode.wrap),
primaryXAxis: CategoryAxis(
// Axis will be rendered based on the index values
interval: 1,
labelRotation: 90,
arrangeByIndex: true
),
primaryYAxis: NumericAxis(
edgeLabelPlacement: EdgeLabelPlacement.shift,
// labelFormat: '{value}k',
axisLine: const AxisLine(width: 0),
majorTickLines: const MajorTickLines(color: Colors.transparent)
),
tooltipBehavior: TooltipBehavior(enable: true),
series: <ChartSeries<DailyCount, String>>[
LineSeries<DailyCount, String>(
animationDuration: 2500,
width: 2,
name: '',
markerSettings: const MarkerSettings(isVisible: true),
dataSource: chartDataDailyCount!,
xValueMapper: (DailyCount sensors, _) => sensors.xaxis,
yValueMapper: (DailyCount sensors, _) => sensors.collectCount,
),
]
),
SizedBox(height:50),
// Column(children: [
// SfCartesianChart(
// plotAreaBorderWidth: 0,
// title: ChartTitle(text: 'Surveyor Progress'),
// legend: Legend(
// isVisible: isCardView ? false : true,
// overflowMode: LegendItemOverflowMode.wrap),
// primaryXAxis: CategoryAxis(
// // Axis will be rendered based on the index values
// interval: 1,
// labelRotation: 90,
// arrangeByIndex: true
// ),
// primaryYAxis: NumericAxis(
// edgeLabelPlacement: EdgeLabelPlacement.shift,
// // labelFormat: '{value}k',
// // minimum: 0,
// // maximum: 12,
// axisLine: const AxisLine(width: 0),
// majorTickLines: const MajorTickLines(color: Colors.transparent)
// ),
// tooltipBehavior: TooltipBehavior(enable: true),
// series: <ChartSeries<SurveyourCount, String>>[
// LineSeries<SurveyourCount, String>(
// animationDuration: 2500,
// width: 2,
// name: '',
// color: Colors.red,
// markerSettings: const MarkerSettings(isVisible: true),
// dataSource: chartDataSurveyourCount,
// xValueMapper: (SurveyourCount sales, _) => sales.dbDateTime1,
// yValueMapper: (SurveyourCount sales, _) => sales.totalSurveyorCount1,
// ),
// LineSeries<SurveyourCount, String>(
// animationDuration: 2500,
// width: 2,
// name: '',
// color: Colors.red,
// markerSettings: const MarkerSettings(isVisible: true),
// dataSource: chartDataSurveyourCount,
// xValueMapper: (SurveyourCount sales, _) => sales.dbDateTime1,
// yValueMapper: (SurveyourCount sales, _) => sales.totalSurveyorCount1,
// ),
// // LineSeries<SurveyourCount, String>(
// // animationDuration: 2500,
// // width: 2,
// // name: '',
// // color: Colors.green,
// // markerSettings: const MarkerSettings(isVisible: true),
// // dataSource: chartDataSurveyourCount,
// // xValueMapper: (SurveyourCount sales, _) => sales.dbDateTime2,
// // yValueMapper: (SurveyourCount sales, _) => sales.totalSurveyorCount2,
// // ),
// // LineSeries<SurveyourCount, String>(
// // animationDuration: 2500,
// // width: 2,
// // name: '',
// // color: Colors.blue,
// // markerSettings: const MarkerSettings(isVisible: true),
// // dataSource: chartDataSurveyourCount,
// // xValueMapper: (SurveyourCount sales, _) => sales.dbDateTime3,
// // yValueMapper: (SurveyourCount sales, _) => sales.totalSurveyorCount3,
// // ),
// // LineSeries<SurveyourCount, String>(
// // animationDuration: 2500,
// // width: 2,
// // name: '',
// // color: Colors.yellow,
// // markerSettings: const MarkerSettings(isVisible: true),
// // dataSource: chartDataSurveyourCount,
// // xValueMapper: (SurveyourCount sales, _) => sales.dbDateTime4,
// // yValueMapper: (SurveyourCount sales, _) => sales.totalSurveyorCount4,
// // ),
// // LineSeries<SurveyourCount, String>(
// // animationDuration: 2500,
// // width: 2,
// // name: '',
// // color: Colors.black,
// // markerSettings: const MarkerSettings(isVisible: true),
// // dataSource: chartDataSurveyourCount,
// // xValueMapper: (SurveyourCount sales, _) => sales.dbDateTime5,
// // yValueMapper: (SurveyourCount sales, _) => sales.totalSurveyorCount5,
// // ),
// // LineSeries<SurveyourCount, String>(
// // animationDuration: 2500,
// // width: 2,
// // name: '',
// // color: Colors.orange,
// // markerSettings: const MarkerSettings(isVisible: true),
// // dataSource: chartDataSurveyourCount,
// // xValueMapper: (SurveyourCount sales, _) => sales.dbDateTime6,
// // yValueMapper: (SurveyourCount sales, _) => sales.totalSurveyorCount6,
// // ),
// // LineSeries<SurveyourCount, String>(
// // animationDuration: 2500,
// // width: 2,
// // name: '',
// // color: Colors.pink,
// // markerSettings: const MarkerSettings(isVisible: true),
// // dataSource: chartDataSurveyourCount,
// // xValueMapper: (SurveyourCount sales, _) => sales.dbDateTime7,
// // yValueMapper: (SurveyourCount sales, _) => sales.totalSurveyorCount7,
// // ),
//
//
// ]
//
// ),
// ]
// ),
//--------------------------------------------
// Container(
// width: 30,
// height: 30 ,
// color: Colors.red,
// ),
// ],)
// FutureBuilder(
// future: futureMonthlyCount,
// builder: (context, snapshot) {
// if (snapshot.hasData) {
// return SfCartesianChart(
// plotAreaBorderWidth: 0,
// title: ChartTitle(text: 'Monthly Progress'),
// legend: Legend(
// isVisible: isCardView ? false : true,
// overflowMode: LegendItemOverflowMode.wrap),
// primaryXAxis: CategoryAxis(
// // Axis will be rendered based on the index values
// interval: 1,
// labelRotation: 90,
// arrangeByIndex: true
// ),
// primaryYAxis: NumericAxis(
// edgeLabelPlacement: EdgeLabelPlacement.shift,
// // labelFormat: '{value}k',
// // minimum: 0,
// // maximum: 12,
// axisLine: const AxisLine(width: 0),
// majorTickLines: const MajorTickLines(color: Colors.transparent)
// ),
// tooltipBehavior: TooltipBehavior(enable: true),
// series: <ChartSeries<MonthlyCount, String>>[
// LineSeries<MonthlyCount, String>(
// animationDuration: 2500,
// width: 2,
// name: '',
// markerSettings: const MarkerSettings(isVisible: true),
//
//
//
//
// dataSource: chartDataMonthlyCount!,
// xValueMapper: (MonthlyCount sales, _) => sales.xaxis,
// yValueMapper: (MonthlyCount sales, _) => sales.collectCount,
// ),
//
// ]
//
// );
// }
// else {
// return CircularProgressIndicator();
// }
// }
// ),
],
);
}
else if (snapshot.hasError) {
// return Text('${snapshot.error}');
return Column(children: [
Padding(
padding: EdgeInsets.all(60),
child:Text('Internet Connection Problem',style:TextStyle(fontSize: 18))),
FlatButton(
child: Text('Refreash', style: TextStyle(fontSize: 20.0),),
onPressed: () {
check().then((intenet) async {
if (intenet != null && intenet) {
setState(() {
futureDailyCount = fetchDailyCount('all','all','all');
});
print('internet Conneciton present');
}else{
print('internet Conneciton Not present');
showAlertDialogInternetNotPresent(context);
}
});
},
),
]);
}
// By default, show a loading spinner.
return Container(
alignment: Alignment.topCenter,
margin: EdgeInsets.only(top: 40),
child: CircularProgressIndicator()
);
}
),
i'm facing issues in line charts. i'm fetching x and y data from sq lite database. and it should set
in line chart.when activity started chart showing blank. but only click on chart value is setting in
chart.
i'm using charts_flutter dart package for implementation.
where i did the mistake. any solutions.
Future graph_initialize() {
Future<List<Map>> noteListFuture1 = dbHelper.get_lactation_curve("${widget.value.tag}");//fetching data from databse
noteListFuture1.then((noteList) {
for(int i=0;i<noteList.length;i++){
print(noteList[i]["Days"].toString()+","+noteList[i]["Milk_Yield"].toString());
milking_data.add( new Sales(noteList[i]["Days"], noteList[i]["Milk_Yield"]));
}
_serieslineData.add(charts.Series(
colorFn: (__, _) => charts.ColorUtil.fromDartColor(Colors.red),
id: 'lac',
data: milking_data,// here data is setting
domainFn: (Sales sales, _) => sales.yearval,
measureFn: (Sales sales, _) => sales.salesval));
setState(() {
});
});}
#override
void initState() {
super.initState();
_serieslineData = List<charts.Series<Sales, int>>();
graph_initialize();//function call
}
Widget show_chart(){
return Padding(
padding: EdgeInsets.all(8),
child: Container(
height: 300,
child: Column(
children: <Widget>[
Text('Lactation Curve',
style: TextStyle(fontSize: 16, fontFamily: 'Montserrat',fontWeight: FontWeight.bold)),
Expanded(
child: charts.LineChart(_serieslineData,
animate: false,
domainAxis: charts.NumericAxisSpec(
tickProviderSpec:
new charts.BasicNumericTickProviderSpec(
desiredTickCount: 11,
),
viewport: charts.NumericExtents(
0,
300,
)),
animationDuration: Duration(seconds: 3),
behaviors: [
charts.ChartTitle('Milk Yield',
behaviorPosition: charts.BehaviorPosition.start),
charts.ChartTitle('Days in Milk',
behaviorPosition: charts.BehaviorPosition.bottom),
charts.ChartTitle(
'',
),
charts.ChartTitle(' ')
])),
Padding(
padding: const EdgeInsets.all(8.0),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceEvenly,
children: <Widget>[label(Colors.red,'Lac'),
label(Colors.lightBlueAccent,'Milk(kg)'),
label(Colors.amber,'A.I'),
label(Colors.green,'Pregnant'),
label(Colors.blueGrey,'Vaccination'),
label(Colors.black,'Treatment'),
],
),
)
],
),
),
);
}
You need a bool loading or isLoading to control because chart data is not ready yet
and when loading == true return CircularProgressIndicator() or Container()
bool loading = false;
Future graph_initialize() {
loading = true;
Future<List<Map>> noteListFuture1 = dbHelper.get_lactation_curve("${widget.value.tag}");//fetching data from databse
noteListFuture1.then((noteList) {
for(int i=0;i<noteList.length;i++){
print(noteList[i]["Days"].toString()+","+noteList[i]["Milk_Yield"].toString());
milking_data.add( new Sales(noteList[i]["Days"], noteList[i]["Milk_Yield"]));
}
_serieslineData.add(charts.Series(
colorFn: (__, _) => charts.ColorUtil.fromDartColor(Colors.red),
id: 'lac',
data: milking_data,// here data is setting
domainFn: (Sales sales, _) => sales.yearval,
measureFn: (Sales sales, _) => sales.salesval));
setState(() {
loading = false;
});
});}
Expanded(
child: loading? CircularProgressIndicator() : charts.LineChart(_serieslineData,
animate: false,
domainAxis: charts.NumericAxisSpec(
tickProviderSpec:
I'm trying to fit pie chart, bar graph and line graph in the same screen in scrollable view
I want to display multiple graphs in a single screen in scrollable view
I used flexible() widget that fitted the graph in a single screen then I tried ListView and SingleChildScrollView but it's not working
Below are the codes of whatever I tried
import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:font_awesome_flutter/font_awesome_flutter.dart';
import 'package:pie_chart/pie_chart.dart';
import 'DonutPieChart.dart';
class HomePage extends StatefulWidget {
final Widget child;
HomePage({Key key, this.child}) : super(key: key);
_HomePageState createState() => _HomePageState();
}
Map<String, double> dataMap = new Map();
class _HomePageState extends State<HomePage>{
List<charts.Series<Pollution, String>> _seriesData;
List<charts.Series<Electricity1, String>> _seriesPieData;
List<charts.Series<Vehicles,int>> _seriesLineData;
List<charts.Series<Electricity, String>>_seriesPieData1;
TabController _tabController;
ScrollController _scrollViewController;
int _counter = 0;
_generateData() {
var data1 = [
new Pollution('June',3),
new Pollution('July',1),
new Pollution('August',5),
];
var data2 = [
new Pollution('June', 1),
new Pollution('July',2),
new Pollution('August',4),
];
var data3 = [
new Pollution('June', 5),
new Pollution('July',3),
new Pollution('August',3),
];
var piedata = [
new Electricity1('Renewable Onsite', 8),
new Electricity1('Renewable Wheeled', 10),
new Electricity1('Purchased Grid', 15),
];
var piedata1 = [
new Electricity('Renewable', 18, Color(0xfffdbe19)),
new Electricity('Purchased Grid', 15, Color(0xff990099)),
];
var linedata = [
new Vehicles(2, 56),
new Vehicles(4, 55),
new Vehicles(6, 60),
new Vehicles(8, 61),
new Vehicles(10, 70),
];
var linedata1 = [
new Vehicles(2, 46),
new Vehicles(4, 45),
new Vehicles(6, 50),
new Vehicles(8, 51),
new Vehicles(10, 60),
];
var linedata2 = [
new Vehicles(2, 24),
new Vehicles(4, 25),
new Vehicles(6, 40),
new Vehicles(8, 45),
new Vehicles(10, 60),
];
final data = [
new LinearSales(0, 100),
new LinearSales(1, 75),
new LinearSales(2, 25),
new LinearSales(3, 5),
];
_seriesData.add(
charts.Series(
id:'LPG-Cooking',
domainFn: (Pollution pollution, _) => pollution.place,
measureFn: (Pollution pollution, _) => pollution.quantity,
data: data1,
),
);
_seriesData.add(
charts.Series(
id:'Diesel',
domainFn: (Pollution pollution, _) => pollution.place,
measureFn: (Pollution pollution, _) => pollution.quantity,
data: data2,
),
);
_seriesData.add(
charts.Series(
id:'LPG-lab',
domainFn: (Pollution pollution, _) => pollution.place,
measureFn: (Pollution pollution, _) => pollution.quantity,
data: data3,
),
);
_seriesPieData.add(
charts.Series(
id:'Pollution',
domainFn: (Electricity1 e, _) => e.emission,
measureFn: (Electricity1 e, _) => e.emission_value,
data: piedata,
// Set a label accessor to control the text of the arc label.
labelAccessorFn: (Electricity1 e, _) => '${e.emission}: ${e.emission_value}',
),
);
_seriesPieData1.add(
charts.Series(
id:'Pollution',
domainFn: (Electricity e, _) => e.emission,
measureFn: (Electricity e, _) => e.emission_value,
colorFn: (Electricity e, _) =>
charts.ColorUtil.fromDartColor(e.colorval),
data: piedata1,
// Set a label accessor to control the text of the arc label.
labelAccessorFn: (Electricity e, _) => '${e.emission}: ${e.emission_value}',
),
);
_seriesLineData.add(
charts.Series(
id: 'Two wheeler',
data: linedata,
domainFn: (Vehicles v, _) => v.month,
measureFn: (Vehicles v, _) => v.emissions,
),
);
_seriesLineData.add(
charts.Series(
colorFn: (__, _) => charts.ColorUtil.fromDartColor(Color(0xff0277BD)),
id: 'Three wheeler',
data: linedata1,
domainFn: (Vehicles v, _) => v.month,
measureFn: (Vehicles v, _) => v.emissions,
),
);
_seriesLineData.add(
charts.Series(
colorFn: (__, _) => charts.ColorUtil.fromDartColor(Color(0xff01579D)),
id: 'Four wheeler',
data: linedata2,
domainFn: (Vehicles v, _) => v.month,
measureFn: (Vehicles v, _) => v.emissions,
),
);
}
#override
void initState() {
// TODO: implement initState
super.initState();
_seriesData = List<charts.Series<Pollution, String>>();
_seriesPieData = List<charts.Series<Electricity1, String>>();
_seriesLineData = List<charts.Series<Vehicles,int>>();
_seriesPieData1= List<charts.Series<Electricity, String>>();
_generateData();
dataMap.putIfAbsent("Flutter", () => 5);
dataMap.putIfAbsent("React", () => 3);
dataMap.putIfAbsent("Xamarin", () => 2);
dataMap.putIfAbsent("Ionic", () => 2);
}
#override
void dispose() {
_tabController.dispose();
_scrollViewController.dispose();
super.dispose();
}
void _incrementCounter() {
setState(() {
// This call to setState tells the Flutter framework that something has
// changed in this State, which causes it to rerun the build method below
// so that the display can reflect the updated values. If we changed
// _counter without calling setState(), then the build method would not be
// called again, and so nothing would appear to happen.
_counter++;
});
}
#override
Widget build(BuildContext context) {
var dpc = DonutPieChart.withSampleData();
return MaterialApp(
home: Scaffold(
body:Center(
child:ListView(
//child:Column(
//children: [
children: <Widget>[
SizedBox(height: 30.0,
child: Text(
'Direct Emissions by lpg-cooking, lpg-lab and diesel (in kg)',style: TextStyle(fontSize: 24.0,fontWeight: FontWeight.bold),),
),
Flexible( flex: 5,
child:
Card(
child: charts.BarChart(
_seriesData,
animate: true,
barGroupingType: charts.BarGroupingType.stacked,
behaviors: [new charts.SeriesLegend()],
animationDuration: Duration(seconds: 1),
),
),
),
SizedBox(height: 30.0,
child:Text(
'CO2 produced by electricity',style: TextStyle(fontSize: 24.0,fontWeight: FontWeight.bold),),
),
Flexible(
flex:5,
child:
Card(
child:Stack(
children:<Widget>[
Container(
//color: Colors.blue,
height: 300.0,
width: 300.0,
child: dpc,
),
Container(
// color: Colors.blue,
height: 300.0,
width: 300.0,
child: PieChart(dataMap: dataMap, showLegends: false,),
)
],
),
),
),
SizedBox(height: 30.0,
child:Text(
'CO2 in kg produced by vehicles',style: TextStyle(fontSize: 24.0,fontWeight: FontWeight.bold),),
),
Flexible(
flex:5,
child:
Card(
child: charts.LineChart(
_seriesLineData,
defaultRenderer: new charts.LineRendererConfig(
includeArea: true, stacked: true),
animate: true,
animationDuration: Duration(seconds: 1),
behaviors: [
new charts.SeriesLegend(),
new charts.ChartTitle('Months',
behaviorPosition: charts.BehaviorPosition.bottom,
titleOutsideJustification:charts.OutsideJustification.middleDrawArea),
]
),
),
),
],
),
),
),
);
}
}
class Pollution {
String place;
int quantity;
Pollution(this.place, this.quantity);
}
class Vehicles {
int month;
double emissions;
Vehicles(this.month, this.emissions);
}
class Electricity{
String emission;
double emission_value;
Color colorval;
Electricity(this.emission,this.emission_value,this.colorval);
}
class Electricity1{
String emission;
double emission_value;
Electricity1(this.emission,this.emission_value);
}
DonutPieChart.dart file
import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;
class DonutPieChart extends StatelessWidget {
final List<charts.Series> seriesList;
final bool animate;
DonutPieChart(this.seriesList, {this.animate});
/// Creates a [PieChart] with sample data and no transition.
factory DonutPieChart.withSampleData() {
return new DonutPieChart(
_createSampleData(),
// Disable animations for image tests.
animate: false,
);
}
#override
Widget build(BuildContext context) {
return new charts.PieChart(seriesList,
animate: animate,
// Configure the width of the pie slices to 60px. The remaining space in
// the chart will be left as a hole in the center.
defaultRenderer: new charts.ArcRendererConfig(arcWidth: 60));
}
/// Create one series with sample hard coded data.
static List<charts.Series<LinearSales, int>> _createSampleData() {
final data = [
new LinearSales(0, 100),
new LinearSales(1, 75),
new LinearSales(2, 25),
new LinearSales(3, 5),
];
return [
new charts.Series<LinearSales, int>(
id: 'Sales',
domainFn: (LinearSales sales, _) => sales.year,
measureFn: (LinearSales sales, _) => sales.sales,
data: data,
)
];
}
}
/// Sample linear data type.
class LinearSales {
final int year;
final int sales;
LinearSales(this.year, this.sales);
}
Try using ListView
A scrollable list of widgets arranged linearly.
return MaterialApp(
home: Scaffold(
body:Center(
child:
// Column(
// children: [
ListView(
children: <Widget>[
SizedBox(height: 30.0,
child: Text(
'Direct Emissions by lpg-cooking, lpg-lab and diesel (in kg)',style: TextStyle(fontSize: 24.0,fontWeight: FontWeight.bold),),
),
Flexible( flex: 5,
child:
Card(
child: charts.BarChart(
_seriesData,
animate: true,
barGroupingType: charts.BarGroupingType.stacked,
behaviors: [new charts.SeriesLegend()],
animationDuration: Duration(seconds: 1),
),
),
),
SizedBox(height: 30.0,
child:Text(
'CO2 produced by electricity',style: TextStyle(fontSize: 24.0,fontWeight: FontWeight.bold),),
),
Flexible(
flex:5,
child:
Card(
child:Stack(
children:<Widget>[
Container(
//color: Colors.blue,
height: 300.0,
width: 300.0,
child: dpc,
),
Container(
// color: Colors.blue,
height: 300.0,
width: 300.0,
child: PieChart(dataMap: dataMap, showLegends: false,),
)
],
),
),
),
SizedBox(height: 30.0,
child:Text(
'CO2 in kg produced by vehicles',style: TextStyle(fontSize: 24.0,fontWeight: FontWeight.bold),),
),
Flexible(
flex:5,
child:
Card(
child: charts.LineChart(
_seriesLineData,
defaultRenderer: new charts.LineRendererConfig(
includeArea: true, stacked: true),
animate: true,
animationDuration: Duration(seconds: 1),
behaviors: [
new charts.SeriesLegend(),
new charts.ChartTitle('Months',
behaviorPosition: charts.BehaviorPosition.bottom,
titleOutsideJustification:charts.OutsideJustification.middleDrawArea),
]
),
),
),
],
),
),
),
);
wrap your Column inside a SingleChildScrollView and use Containers with the desired height instead of Flexible.
Don't forget to set mainAxisSize: MainAxisSize.min to your Column.
#override
Widget build(BuildContext context) {
var dpc = DonutPieChart.withSampleData();
return MaterialApp(
home: Scaffold(
body: SafeArea(
child: SingleChildScrollView(
child: Column(
mainAxisSize: MainAxisSize.min,
children: <Widget>[
SizedBox(
height: 30.0,
child: Text(
'Direct Emissions by lpg-cooking, lpg-lab and diesel (in kg)',
style: TextStyle(fontSize: 24.0, fontWeight: FontWeight.bold),
),
),
Container(
height: 300,
child: charts.BarChart(
_seriesData,
animate: true,
barGroupingType: charts.BarGroupingType.stacked,
behaviors: [charts.SeriesLegend()],
animationDuration: Duration(seconds: 1),
),
),
SizedBox(
height: 30.0,
child: Text(
'CO2 produced by electricity',
style: TextStyle(fontSize: 24.0, fontWeight: FontWeight.bold),
),
),
Container(
height: 300,
width: 300,
child: Card(
child: Stack(
children: <Widget>[
Container(child: dpc),
Container(child: dpc),
],
),
),
),
SizedBox(
height: 30.0,
child: Text(
'CO2 in kg produced by vehicles',
style: TextStyle(fontSize: 24.0, fontWeight: FontWeight.bold),
),
),
Container(
height: 300,
child: charts.LineChart(_seriesLineData,
defaultRenderer: charts.LineRendererConfig(
includeArea: true, stacked: true),
animate: true,
animationDuration: Duration(seconds: 1),
behaviors: [
charts.SeriesLegend(),
charts.ChartTitle('Months',
behaviorPosition: charts.BehaviorPosition.bottom,
titleOutsideJustification:
charts.OutsideJustification.middleDrawArea),
]),
),
],
),
),
),
),
);
}