Pie chart in flutter - flutter

I am new to the flutter and i am trying implement Pie chart(" Donut chart") but is it not working well. I saw some tutorials, but they are used short cut way.
Please help me in implementing a pie chart

add dependency in pubspec.yaml
dependencies: charts_flutter: ^0.9.0
/// Donut chart example. This is a simple pie chart with a hole in the middle.
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:flutter/material.dart';
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);
}

Related

Flutter syncfusion Linechart re-draw line between beginning and ending series data

I use syncfusion chart for flutter. I have json data on php api at my server.
I had this data in flutter api connect.
My json data structure is like this:
{
"tablo": "neyzi",
"cinsiyet": "erkek",
"boy": {
"P3": [
{
"0.0": 45.9,
"3.0": 56.2,
"6.0": 62.8,
"9.0": 67.4,
"12.0": 70.8,
"15.0": 73.8,
"18.0": 76.4
}
],
},
}
I use this code for prepare data for chart:
import 'package:flutter/material.dart';
import 'package:pediatrirutinmobil/pers_chart/chart_olcumdizisi.dart';
import 'package:syncfusion_flutter_charts/charts.dart';
import 'chart_api.dart';
class PersentilChartRepository{
static PersentilChartApiClient _persentilchartApiClient = PersentilChartApiClient();
static List<OlcumDizisi> _p3 =[];
static Future apiden_data_getir ()async{
return await _persentilchartApiClient.veriyigetir();
}
static Future<List<OlcumDizisi>> persentilListesi ()async{
}
static List boyListesi() {
apiden_data_getir().then((value) async{
var P3e = await value.boy.P3[0];
for (final mapEntry in P3e.entries) {
final key = await double.parse(mapEntry.key.toString());
final double value = await double.parse(mapEntry.value.toString());
if (key<=limit){
_p3.add(OlcumDizisi(key, value));
}
}
// _p3.addAll([OlcumDizisi(6,60),OlcumDizisi(7, 80),OlcumDizisi(10, 90)]);
*/
} );
List<ChartSeries<OlcumDizisi,double>> chartSeries = [
new LineSeries<OlcumDizisi, double>(
name: 'P3',
xValueMapper: (OlcumDizisi olcum, _) => olcum.yasay,
yValueMapper: (OlcumDizisi olcum, _) => olcum.olcum,
dataSource: _p3,
color: Colors.red,
width: 0.75,
)
];
return chartSeries;
}
}
class OlcumDizisi {
final double yasay;
final double olcum;
OlcumDizisi(this.yasay, this.olcum);
}
And I use chart page like this:
import 'dart:core';
import 'package:easy_localization/easy_localization.dart';
import 'package:flutter/material.dart';
import 'package:pediatrirutinmobil/pers_chart/chart_repo.dart';
import 'package:syncfusion_flutter_charts/charts.dart';
class StackedAreaLineChart extends StatefulWidget {
#override
State<StackedAreaLineChart> createState() => _StackedAreaLineChartState();
}
class _StackedAreaLineChartState extends State<StackedAreaLineChart> {
List _charset;
#override
void initState() async{
_charset = await PersentilChartRepository.boyListesi();
setState(() {
});
// TODO: implement initState
super.initState();
}
#override
void dispose() {
_charset;
// TODO: implement dispose
super.dispose();
}
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(),
body: SafeArea(
child: Center(
child: Container(
child: SfCartesianChart(
primaryXAxis: CategoryAxis(),
primaryYAxis: NumericAxis(
numberFormat: NumberFormat.decimalPattern()
),
// Chart title
title: ChartTitle(text: 'TITLE'),
// Enable legend
legend: Legend(isVisible: true),
// Enable tooltip
tooltipBehavior: TooltipBehavior(enable: true),
series:_charset,
enableSideBySideSeriesPlacement: false,
),
),
),
),
);
}
}
so after then all of this page my chart build graphic but if I back another page and reopen chart page Linechart re-build new line beginning point and ending point.
like this:
this
and this
If i use static List data in chart page its perfect but i use static data in future code like this
apiden_data_getir().then((value) async{
_p3.addAll([OlcumDizisi(6,60),OlcumDizisi(7, 80),OlcumDizisi(10, 90)]);
} );
final result same...
is there any idea.
If you have different solution binding api line chart so I thank you for it.
We talk on github and
static Future apiden_data_getir() async {
///this code
if (_p3.isNotEmpty) {
_p3.clear();
}
/// helpfull it's work
final String jsonString = await getJsonFromAssets();
final dynamic jsonResponse = json.decode(jsonString);
var p3e = jsonResponse['boy']['P3'][0];
The problem seems to be with your init state.
Every time you visit the graph page, the same data gets added to the data source repeatedly, creating a closed loop within the graph. You can verify that by putting a debugger point at this line series:_charset to see the repeating values added to the series.
Try wrapping your SfCartesianChart widget with a Future builder and fetching data there instead of making an API call in the initState.

The argument type 'List<Series<dynamic, dynamic>>' can't be assigned to the parameter type 'List<Series<dynamic, String>>

I have an issue with this flutter simple chart code. Showing this error while I try to run the code. Please can anyone help me in this....
The argument type 'List<Series<dynamic, dynamic>>' can't be assigned to the parameter type 'List<Series<dynamic, String>>
This is the code sample:
//Bar chart example
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:flutter/material.dart';
class SimpleBarChart extends StatelessWidget {
final List<charts.Series> seriesList;
final bool animate;
SimpleBarChart(this.seriesList, {this.animate = false});
/// Creates a [BarChart] with sample data and no transition.
factory SimpleBarChart.withSampleData() {
return new SimpleBarChart(
_createSampleData(),
// Disable animations for image tests.
animate: false,
);
}
#override
Widget build(BuildContext context) {
return new charts.BarChart(
seriesList,
animate: animate,
);
}
/// Create one series with sample hard coded data.
static List<charts.Series<OrdinalSales, String>> _createSampleData() {
final data = [
new OrdinalSales('Today', 55),
new OrdinalSales('Yesterday', 25),
new OrdinalSales('2 days', 100),
new OrdinalSales('24 June', 75),
new OrdinalSales('23 June', 75),
new OrdinalSales('23 June', 75),
new OrdinalSales('22 June', 75),
];
return [
new charts.Series<OrdinalSales, String>(
id: 'Sales',
colorFn: (_, __) => charts.MaterialPalette.blue.shadeDefault,
domainFn: (OrdinalSales sales, _) => sales.year,
measureFn: (OrdinalSales sales, _) => sales.sales,
data: data,
)
];
}
}
/// Sample ordinal data type.
class OrdinalSales {
final String year;
final int sales;
OrdinalSales(this.year, this.sales);
}
Launching lib\main.dart on Chrome in debug mode... Waiting for connection from debug service on Chrome... lib/widgets/barChart.dart:24:7: Error: The argument type 'List<Series<dynamic, dynamic>>' can't be assigned to the parameter type 'List<Series<dynamic, String>>'.
- 'List' is from 'dart:core'.
- 'Series' is from 'package:charts_common/src/data/series.dart' ('/C:/flutter/.pub-cache/hosted/pub.dartlang.org/charts_common-0.11.0/lib/src/data/series.dart').
seriesList,
^ Failed to compile application.
Change your seriesList variable type from:
final List<charts.Series> seriesList;
To:
final List<charts.Series<dynamic, String>> seriesList;
This will work fine.

Error: "1 positional argument(s) expected, but 0 found" flutter dart error

I'm trying to build an app with some charts, and I started with this example, but it doesn't have the first part that initiates the app, so I tried adding:
void main() {
runApp(SimpleTimeSeriesChart());
}
but I get
1 positional argument(s) expected, but 0 found.
Try adding the missing arguments.
in the second line. I don't know what I am doing wrong. Can anyone please help me explain what am I doing wrong and what is the solution? The message is pretty clear, but I don't know which argument I need to add. Also, can anyone point me to some documentation about this particular issue? Thank you!
import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart'
as charts;
void main() {
runApp(SimpleTimeSeriesChart());
}
class SimpleTimeSeriesChart extends StatelessWidget {
final List < charts.Series > seriesList;
final bool animate;
SimpleTimeSeriesChart(this.seriesList, {
this.animate
});
/// Creates a [TimeSeriesChart] with sample data and no transition.
factory SimpleTimeSeriesChart.withSampleData() {
return new SimpleTimeSeriesChart(
_createSampleData(),
// Disable animations for image tests.
animate: false,
);
}
#override
Widget build(BuildContext context) {
return new charts.TimeSeriesChart(
seriesList,
animate: animate,
// Optionally pass in a [DateTimeFactory] used by the chart. The factory
// should create the same type of [DateTime] as the data provided. If none
// specified, the default creates local date time.
dateTimeFactory: const charts.LocalDateTimeFactory(),
);
}
/// Create one series with sample hard coded data.
static List < charts.Series < TimeSeriesSales, DateTime >> _createSampleData() {
final data = [
new TimeSeriesSales(new DateTime(2017, 9, 19), 5),
new TimeSeriesSales(new DateTime(2017, 9, 26), 25),
new TimeSeriesSales(new DateTime(2017, 10, 3), 100),
new TimeSeriesSales(new DateTime(2017, 10, 10), 75),
];
return [
new charts.Series < TimeSeriesSales, DateTime > (
id: 'Sales',
colorFn: (_, __) => charts.MaterialPalette.blue.shadeDefault,
domainFn: (TimeSeriesSales sales, _) => sales.time,
measureFn: (TimeSeriesSales sales, _) => sales.sales,
data: data,
)
];
}
}
/// Sample time series data type.
class TimeSeriesSales {
final DateTime time;
final int sales;
TimeSeriesSales(this.time, this.sales);
}
You need to pass the first argument since it's not optional SimpleTimeSeriesChart(this.seriesList
void main() {
runApp(SimpleTimeSeriesChart([]));
}
You can read more about Dart parameters here

I have facing below problem when scroll then render donut chart every time

I have facing below problem when scroll then render donut chart every time.
This below Renderer Param remove then not facing this problem but i have required donut chart.
defaultRenderer: new charts.ArcRendererConfig(
arcWidth: 60,
arcRendererDecorators: [charts.ArcLabelDecorator()])
),
Hereby, I am attaching Donut Chart code & Image:-
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:flutter/material.dart';
import 'package:flutter_basf_hk_app/model/LinearSales.dart';
class PieOutsideLabelChart extends StatelessWidget {
final List<charts.Series> seriesList;
final bool animate;
PieOutsideLabelChart(this.seriesList, {this.animate});
/// Creates a [PieChart] with sample data and no transition.
factory PieOutsideLabelChart.withSampleData(List<LinearSales> data,
bool isAnimation) {
return new PieOutsideLabelChart(
_createSampleData(data),
// Disable animations for image tests.
animate: isAnimation,
);
}
#override
Widget build(BuildContext context) {
return Container(
child: new charts.PieChart(seriesList,
animate: animate,
defaultRenderer: new charts.ArcRendererConfig(
arcWidth: 60,
arcRendererDecorators: [charts.ArcLabelDecorator()])
),
);
}
/// Create one series with sample hard coded data.
static List<charts.Series<LinearSales, int>> _createSampleData(List<LinearSales> data) {
print('=========PIE==========_createSampleData=====');
return [
new charts.Series<LinearSales, int>(
id: 'Sales',
domainFn: (LinearSales sales, _) => sales.year,
measureFn: (LinearSales sales, _) => sales.sales,
data: data,
colorFn: (LinearSales sales, _) => sales.color,
labelAccessorFn: (LinearSales sales, _) => '${sales.sales}',
)
];
}
}
This might not be the type of help your looking for, thus,
Check out this more commonly used chart plugin called syncfusion_flutter_charts.
https://pub.dev/packages/syncfusion_flutter_charts#-readme-tab-

Flutter Google Chart Gauge - place label within center

I am looking at charts_flutter package. I need to implement a gauge chart, with a single segment and its label value at the gauge's center. See the mockup file below, where three charts from the required type are placed in a row:
Using Google chart gauge sample, I was able to implement the required gauge, however, I am struggling to set the label as per the requirement.
Below is the class, I use for the gauge, any help / hints how to add the label would be greatly appreciated:
/// Gauge chart example, where the data does not cover a full revolution in the
/// chart.
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:flutter/material.dart';
import 'dart:math';
class GaugeChart extends StatelessWidget {
final List<charts.Series> seriesList;
final bool animate;
GaugeChart(this.seriesList, {this.animate});
factory GaugeChart.fromValue(
{#required double value, #required Color color, bool animate}) {
return GaugeChart(
_createDataFromValue(value, color),
// Disable animations for image tests.
animate: animate,
);
}
#override
Widget build(BuildContext context) {
return charts.PieChart(
seriesList,
animate: animate,
// Configure the width of the pie slices to 30px. The remaining space in
// the chart will be left as a hole in the center. Adjust the start
// angle and the arc length of the pie so it resembles a gauge.
defaultRenderer: charts.ArcRendererConfig(
arcWidth: 20,
startAngle: 3 / 5 * pi,
arcLength: 9 / 5 * pi,
//arcRendererDecorators: [charts.ArcLabelDecorator(labelPosition: charts.ArcLabelPosition.outside)],
),
);
}
static List<charts.Series<GaugeSegment, String>> _createDataFromValue(
double value, Color color) {
double toShow = (1 + value) / 2;
final data = [
GaugeSegment('Main', toShow, color),
GaugeSegment('Rest', 1 - toShow, Colors.transparent),
];
return [
charts.Series<GaugeSegment, String>(
id: 'Segments',
domainFn: (GaugeSegment segment, _) => segment.segment,
measureFn: (GaugeSegment segment, _) => segment.value,
colorFn: (GaugeSegment segment, _) => segment.color,
// Set a label accessor to control the text of the arc label.
labelAccessorFn: (GaugeSegment segment, _) =>
segment.segment == 'Main' ? '${segment.value}' : null,
data: data,
)
];
}
}
/// data type.
class GaugeSegment {
final String segment;
final double value;
final charts.Color color;
GaugeSegment(this.segment, this.value, Color color)
: this.color = charts.Color(
r: color.red, g: color.green, b: color.blue, a: color.alpha);
}
This is how the class can be used:
// value can take values between -1 and 1
GaugeChart.fromValue(value: 0.34, color: Colors.red)
We achieved this using a Stack:
return Container(
width: 120,
height: 120,
child: Stack(children: [
GaugeChart(_getChartData()),
Center(
child: Text(
'$percent',
))
]));