Flutter-unable to set coordinates in line charts? - flutter

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:

Related

How to change the size of the text in a Pie Chart in flutter?

I have a donut graphic but the texts are too small and I have not been able to make them bigger. it is a "PieChart" chart. I have my data segmented into A, B, C, D, E, F. I need to change text size, I am using a tablet size device and that is why the graph should look large, however the texts do not change size and I do not know how to achieve that my code is as follows:
_RegZonesCircularTabletState createState() => _RegZonesCircularTabletState();
}
class GradesData {
final String gradeSymbol;
final int numberOfStudents;
final charts.Color color;
GradesData(this.gradeSymbol, this.numberOfStudents, this.color);
}
#override
Widget build(BuildContext context) {
// TODO: implement build
throw UnimplementedError();
}
class _RegZonesCircularTabletState extends State<RegZonesCircularTablet> {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
backgroundColor: Colors.green,
centerTitle: true,
title: Text("RegiĆ³n o Zona"),
),drawer: LateralMenu(),
body: ListView(children: <Widget> [
Container(
height: 750,
child:new charts.PieChart(
_getSeriesData(),
animate: true,
defaultRenderer: new charts.ArcRendererConfig(
arcWidth: 200,//ancho de la dona
arcRendererDecorators: [new charts.ArcLabelDecorator(),]
),
),
),
],),
floatingActionButton:Container(
height: 110.0,
width: 110.0,
child: FloatingActionButton(
onPressed: () {
// Add your onPressed code here!
},
child: const Icon(Icons.calendar_today,size: 50),
backgroundColor: Colors.black,
elevation: 5.0,
) ,)
);
}
}
final data = [
GradesData('A', 190,charts.MaterialPalette.indigo.shadeDefault),
GradesData('B', 230,charts.MaterialPalette.purple.shadeDefault),
GradesData('C', 150,charts.MaterialPalette.cyan.shadeDefault),
GradesData('D', 73,charts.MaterialPalette.lime.shadeDefault),
GradesData('E', 31,charts.MaterialPalette.teal.shadeDefault),
GradesData('Fail', 13,charts.MaterialPalette.gray.shadeDefault),
];
_getSeriesData() {
List<charts.Series<GradesData, String>> series = [
charts.Series(
id: "Grades",
data: data,
labelAccessorFn: (GradesData row, _) => '${row.gradeSymbol}: ${row.numberOfStudents}',
domainFn: (GradesData grades, _) => grades.gradeSymbol,
measureFn: (GradesData grades, _) => grades.numberOfStudents,
colorFn: (GradesData grades, _) => grades.color,
)
];
return series;
}
The chart is for tablet
Thanks, I'm a beginner, sorry for the trouble
Using the below code while creating charts.Series, we can manage the text style of the chart
charts.Series<MyModel, String>(
//....
outsideLabelStyleAccessorFn: (_, __) => const charts.TextStyleSpec(
fontSize: 16,
color: charts.MaterialPalette.black,
fontFamily: 'MyFont'
),
insideLabelStyleAccessorFn: (_, __) => const charts.TextStyleSpec(
fontSize: 16,
color: charts.MaterialPalette.white,
fontFamily: 'MyFont'
),
);
And don't forget to add this in PieChart widget
defaultRenderer: charts.ArcRendererConfig(
arcRendererDecorators: [charts.ArcLabelDecorator()],
),

Values are not displaying on Flutter Charts

I am fetching data from firebase's real-time database to show in flutter charts but after function calling the value returned is still null/0. When getDuration() is called the data is shown inside the function but it is not returning. As I am new to Flutter, I don't understand the problem occurring.
If I hard code the values, then it shows on the chart but if I call function then it doesn't display bars.
My database looks like this:
I am fetching duration under the date to show inside the flutter chart on the y-axis with weekdays as the x-axis.
My code for flutter chart:
void initState() {
getSeizureHistory();
//Charts
setState(() {
var data = [
addcharts(sevenDay.substring(0, 2), getDuration(seven),
charts.ColorUtil.fromDartColor(const Color(0xffe8e5af))),
addcharts(sixDay.substring(0, 2), getDuration(six),
charts.ColorUtil.fromDartColor(const Color(0xffe8e5af))),
addcharts(fiveDay.substring(0, 2), getDuration(five),
charts.ColorUtil.fromDartColor(const Color(0xffe8e5af))),
addcharts(fourDay.substring(0, 2), getDuration(four),
charts.ColorUtil.fromDartColor(const Color(0xffe8e5af))),
addcharts(threeDay.substring(0, 2), getDuration(three),
charts.ColorUtil.fromDartColor(const Color(0xffe8e5af))),
addcharts(twoDay.substring(0, 2), getDuration(two),
charts.ColorUtil.fromDartColor(const Color(0xffe8e5af))),
addcharts(oneDay.substring(0, 2), getDuration(one.toString()),
charts.ColorUtil.fromDartColor(const Color(0xffe8e5af))),
];
var series = [
charts.Series(
domainFn: (addcharts addcharts, _) => addcharts.weeks,
measureFn: (addcharts addcharts, _) => addcharts.duration,
colorFn: (addcharts addcharts, _) => addcharts.barColor,
id: 'addcharts',
data: data,
),
];
chartdisplay = charts.BarChart(
series,
animationDuration: Duration(microseconds: 2000),
);
});
}
getDuration() function:
int _duration = 0;
int getDuration(String date) {
//print("Date $date");
//load the data from firebase and add to the list
fb.reference()
..child(cuser.uid)
.child('Seizure_history')
.child(date)
.once()
.then((DataSnapshot snapshot) {
var data = snapshot.value;
list = List();
if (data != null) {
data.forEach((key, value) {
EventList seizure_history = new EventList(
seiz_duration: value['duration'],
dateTime: value['datetime'],
key: key,
);
list.add(seizure_history);
setState(()
{
_duration = int.parse(list[0].seiz_duration);
});
print("Duration $_duration");
return _duration;
});
}
});
}
Inside widget:
Center(
child: Container(
height: size.width * 0.80,
width: size.width * 0.90,
padding: EdgeInsets.all(11.0),
child: Card(
elevation: 5,
shape: RoundedRectangleBorder(
borderRadius: BorderRadius.circular(30),
),
child: Padding(
padding: const EdgeInsets.all(8.0),
child: Column(
children: <Widget>[
Text(
"Seizure Duration",
style: TextStyle(
fontFamily: 'Montserrat',
fontSize: 12,
color: const Color(0xff232425),
fontWeight: FontWeight.w600,
),
textAlign: TextAlign.center,
),
Expanded(
child: chartdisplay,
)
],
),
),
),),
),
addcharts class:
class addcharts {
final String weeks;
final int duration;
final charts.Color barColor;
addcharts(this.weeks, this.duration, this.barColor);
}
On console, it is showing:
But on charts, it is still null:

How To Create Custom Line Chart in Flutter?

I just want to line chart in my flutter application like below image.
Here is my code but the result output is normal. i am using charts_flutter: ^0.9.0 packages.
import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:flutter_screenutil/screenutil.dart';
import 'data/sale_data.dart';
class LineChart extends StatelessWidget {
// Defining the data
final data = [
new SalesData(1, 7),
new SalesData(2, 19),
new SalesData(3, 6),
new SalesData(4, 3),
new SalesData(5, 10),
new SalesData(6, 21),
new SalesData(7, 3),
new SalesData(8, 10),
new SalesData(9, 5),
new SalesData(10, 15),
new SalesData(11, 8),
new SalesData(12, 12),
new SalesData(13, 6),
new SalesData(14, 18),
new SalesData(15, 4),
new SalesData(16, 8),
new SalesData(17, 3),
new SalesData(18, 12),
new SalesData(19, 7),
new SalesData(20, 3),
new SalesData(21, 8),
new SalesData(22, 12),
new SalesData(23, 6),
new SalesData(24, 18),
new SalesData(25, 4),
new SalesData(26, 8),
new SalesData(27, 3),
new SalesData(28, 12),
new SalesData(29, 7),
new SalesData(30, 3),
new SalesData(31, 8),
new SalesData(32, 12),
new SalesData(33, 6),
new SalesData(34, 18),
new SalesData(35, 4),
new SalesData(36, 8),
new SalesData(37, 3),
new SalesData(38, 12),
new SalesData(39, 7),
new SalesData(40, 3),
];
_getSeriesData() {
List<charts.Series<SalesData, int>> series = [
charts.Series(
//dot color is fillcolorfn
fillColorFn: (SalesData series, _) =>
charts.MaterialPalette.green.shadeDefault,
//seriesColor: charts.ColorUtil.fromDartColor(Colors.red),
id: "Sales",
data: data,
patternColorFn: (SalesData series, _) => charts.MaterialPalette.white,
// areaColorFn: ((SalesData series, _) => charts.MaterialPalette.black),
domainUpperBoundFn: (SalesData series, _) => series.domainUpper,
domainLowerBoundFn: (SalesData series, _) => series.domainLower,
measureUpperBoundFn: (SalesData series, _) => series.measureUpper,
measureLowerBoundFn: (SalesData series, _) => series.measureLower,
domainFn: (SalesData series, _) => series.year,
measureFn: (SalesData series, _) => series.sales,
colorFn: (SalesData series, _) =>
charts.MaterialPalette.red.shadeDefault),
];
return series;
}
#override
Widget build(BuildContext context) {
return Container(
height: ScreenUtil().setHeight(800),
child: Card(
color: Colors.white,
child: Padding(
padding: EdgeInsets.only(
left: ScreenUtil().setWidth(20),
right: ScreenUtil().setWidth(20),
),
child: Column(
children: <Widget>[
// Text(
// "Sales of a company over the years",
// style: TextStyle(fontWeight: FontWeight.bold),
// ),
// SizedBox(
// height: 20,
// ),
Padding(
padding: EdgeInsets.only(
top: ScreenUtil().setWidth(20),
),
child: Align(
alignment: Alignment.centerRight,
child: Container(
alignment: Alignment.topRight,
color: Colors.white,
height: ScreenUtil().setHeight(50),
width: ScreenUtil().setWidth(100),
child: Text("hello"),
),
),
),
Expanded(
child: new charts.LineChart(
_getSeriesData(),
animate: true,
// domainAxis: new charts.NumericAxisSpec(
// // Set the initial viewport by providing a new AxisSpec with the
// // desired viewport, in NumericExtents.
// viewport: new charts.NumericExtents(0.0, 40.0)),
),
)
],
),
),
),
);
}
}
my output image is below
I've checked the two images that you've shared and the only difference that I can see seems to only be different colors used on those charts. You can try using fl_chart plugin to see if it fits your use case. With fl_chart, it allows you to modify the charts color as detailed on the docs.

How to create custom LegendContentBuilder with charts_flutter library to show and hide series depond on selection?

I used charts_flutter to create BarChart, at current time i want to customise that to build a barChart like below chart:
Here i want to do below options:
show/hide series when i click on legend which i created in CustomLegend (i create that in my code with class name -> CustomLegendBuilder)
set custom color to text of secondaryMeasureAxis and primaryMeasureAxis (i have two axis in right and left)
Show value of column when tap on that column (like a bubble message to show maximum data value of that column)
don't expand width of column when i hide one of series(i want to set specific width to column)
Please see my Code:
pubspec.yaml :
dev_dependencies:
flutter_test:
sdk: flutter
charts_flutter: ^0.9.0
series_legend_options.dart :
import 'dart:math';
import 'package:charts_common/src/chart/common/behavior/legend/legend.dart';
import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;
const Color blueColor = Color(0xff1565C0);
const Color orangeColor = Color(0xffFFA000);
class LegendOptions extends StatelessWidget {
final List<charts.Series> seriesList;
static const secondaryMeasureAxisId = 'secondaryMeasureAxisId';
final bool animate;
LegendOptions(this.seriesList, {this.animate});
factory LegendOptions.withSampleData() {
return LegendOptions(
_createSampleData(),
// Disable animations for image tests.
animate: false,
);
}
#override
Widget build(BuildContext context) {
return charts.BarChart(
seriesList,
animate: animate,
barGroupingType: charts.BarGroupingType.grouped,
defaultRenderer: charts.BarRendererConfig(
cornerStrategy: const charts.ConstCornerStrategy(50)),
primaryMeasureAxis: charts.NumericAxisSpec(
tickProviderSpec: charts.BasicNumericTickProviderSpec(
desiredMinTickCount: 6,
desiredMaxTickCount: 10,
),
),
secondaryMeasureAxis: charts.NumericAxisSpec(
tickProviderSpec: charts.BasicNumericTickProviderSpec(
desiredTickCount: 6, desiredMaxTickCount: 10)),
selectionModels: [
charts.SelectionModelConfig(
changedListener: (charts.SelectionModel model) {
if (model.hasDatumSelection)
print(model.selectedSeries[0]
.measureFn(model.selectedDatum[0].index));
})
],
behaviors: [
charts.SeriesLegend.customLayout(
CustomLegendBuilder(),
position: charts.BehaviorPosition.top,
outsideJustification: charts.OutsideJustification.start,
),
],
);
}
static List<charts.Series<OrdinalSales, String>> _createSampleData() {
final desktopSalesData = [
OrdinalSales('2/14', 29),
OrdinalSales('2/15', 25),
OrdinalSales('2/16', 100),
OrdinalSales('2/17', 75),
OrdinalSales('2/18', 70),
OrdinalSales('2/19', 70),
];
final tabletSalesData = [
OrdinalSales('2/14', 10),
OrdinalSales('2/15', 25),
OrdinalSales('2/16', 8),
OrdinalSales('2/17', 20),
OrdinalSales('2/18', 38),
OrdinalSales('2/19', 70),
];
return [
charts.Series<OrdinalSales, String>(
id: 'expense',
domainFn: (OrdinalSales sales, _) => sales.year,
measureFn: (OrdinalSales sales, _) => sales.sales,
data: desktopSalesData,
colorFn: (_, __) => charts.ColorUtil.fromDartColor(orangeColor),
labelAccessorFn: (OrdinalSales sales, _) =>
'expense: ${sales.sales.toString()}',
displayName: "Expense"),
charts.Series<OrdinalSales, String>(
id: 'income',
domainFn: (OrdinalSales sales, _) => sales.year,
measureFn: (OrdinalSales sales, _) => sales.sales,
data: tabletSalesData,
colorFn: (_, __) => charts.ColorUtil.fromDartColor(blueColor),
displayName: "Income",
)..setAttribute(charts.measureAxisIdKey, secondaryMeasureAxisId),
];
}
}
//Here is my CustomLegendBuilder
class CustomLegendBuilder extends charts.LegendContentBuilder {
#override
Widget build(BuildContext context, LegendState<dynamic> legendState,
Legend<dynamic> legend,
{bool showMeasures}) {
return Row(
mainAxisAlignment: MainAxisAlignment.center,
crossAxisAlignment: CrossAxisAlignment.center,
mainAxisSize: MainAxisSize.min,
children: legend.chart.currentSeriesList
.map<Widget>((e) => InkWell(
//Here i Want to show and hide series when click on the legend
onTap: () {},
child: Container(
padding:
EdgeInsets.symmetric(horizontal: 10, vertical: 5),
margin: EdgeInsets.all(5),
decoration: BoxDecoration(
color: Colors.grey,
borderRadius: BorderRadius.all(Radius.circular(100)),
),
child: Text(
e.displayName,
style: TextStyle(color: Colors.white),
)),
))
.toList()
..add(Spacer())
..add(Transform.rotate(
angle: 90 * (pi / 180),
child: Icon(
Icons.tune,
size: 30,
color: Colors.red,
),
)));
}
}
////////////////////////////////
class OrdinalSales {
final String year;
final int sales;
OrdinalSales(this.year, this.sales);
}
and main.dart :
import 'package:flutter/material.dart';
import 'series_legend_options.dart';
void main(){
runApp(MyApp());
}
class MyApp extends StatefulWidget {
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
#override
Widget build(BuildContext context) {
return MaterialApp(
debugShowCheckedModeBanner: false,
home: HomeWidget(),
);
}
}
class HomeWidget extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
body: Center(
child: Container(
margin: EdgeInsets.all(20),
height: 300,
child: LegendOptions.withSampleData(),
),
),
);
}
}
finally here is my result :
Please help me if you worked with charts_flutter library ,
Thank you very much :)
I am pretty sure there must be a better way (cleaner, more organized) to do it, but I merged your code with flutter_charts open source code and got the colors to be set correctly and the labels to be reactive to the clicks on it to hide or show variables. Here is the example:
/// Custom legend builder
class CustomLegendBuilder extends charts.LegendContentBuilder {
/// Convert the charts common TextStlyeSpec into a standard TextStyle.
TextStyle _convertTextStyle(
bool isHidden, BuildContext context, common.TextStyleSpec textStyle) {
return new TextStyle(
inherit: true,
fontFamily: textStyle?.fontFamily,
fontSize:
textStyle?.fontSize != null ? textStyle.fontSize.toDouble() : null,
color: Colors.white);
}
Widget createLabel(BuildContext context, common.LegendEntry legendEntry,
common.SeriesLegend legend, bool isHidden) {
TextStyle style =
_convertTextStyle(isHidden, context, legendEntry.textStyle);
Color color = charts.ColorUtil.toDartColor(legendEntry.color) ?? Colors.blue;
return new GestureDetector(
child: Container(
height: 30,
width: 90,
decoration: BoxDecoration(
borderRadius: BorderRadius.circular(20),
color: isHidden ? (color).withOpacity(0.26): color,
),
child: Center(child: Text(legendEntry.label, style: style))),
onTapUp: makeTapUpCallback(context, legendEntry, legend));
}
GestureTapUpCallback makeTapUpCallback(BuildContext context,
common.LegendEntry legendEntry, common.SeriesLegend legend) {
return (TapUpDetails d) {
switch (legend.legendTapHandling) {
case common.LegendTapHandling.hide:
final seriesId = legendEntry.series.id;
if (legend.isSeriesHidden(seriesId)) {
// This will not be recomended since it suposed to be accessible only from inside the legend class, but it worked fine on my code.
legend.showSeries(seriesId);
} else {
legend.hideSeries(seriesId);
}
legend.chart.redraw(skipLayout: true, skipAnimation: false);
break;
case common.LegendTapHandling.none:
default:
break;
}
};
}
#override
Widget build(BuildContext context, common.LegendState legendState,
common.Legend legend,
{bool showMeasures}) {
final entryWidgets = legendState.legendEntries.map((legendEntry) {
var isHidden = false;
if (legend is common.SeriesLegend) {
isHidden = legend.isSeriesHidden(legendEntry.series.id);
}
return createLabel(context, legendEntry, legend as common.SeriesLegend, isHidden);
}).toList();
return Padding(
padding: const EdgeInsets.only(right: 40.0, top: 10),
child: Row(
mainAxisAlignment: MainAxisAlignment.spaceBetween,
crossAxisAlignment: CrossAxisAlignment.center,
children: entryWidgets),
);
}
}
About the value you want to be shown on click, maybe this is what you are looking for. I made it work with the CustomCircleSymbolRenderer. You will see that the TextElement is hardcoded to "1". To actualize it you can save a variable on your chart class and call its content:
class MyChart extends StatelessWidget {
final List data;
static String pointerValue;
MyChart(this.data);
Inside the chart, below "behaviours: [],":
selectionModels: [
SelectionModelConfig(changedListener: (SelectionModel model) {
if (model.hasDatumSelection)
pointerValue = model.selectedSeries[0]
.measureFn(model.selectedDatum[0].index)
.toString();
})
],
Then on the custom renderer:
canvas.drawText(
TextElement(MyChart.pointerValue, style: textStyle),
(bounds.left).round(),
(bounds.top - 28).round());
I found an example on internet some time ago, but I am not sure where.
/ 4. About the axis and width of column I have no suggestions.

How to convert below code in scrollable view?

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),
]),
),
],
),
),
),
),
);
}