How to change Y or X axis label in Flutter? - flutter

I am trying to change my Y-axis label from number like 60,000 to 60k. Currently, I am using Charts_Flutter dependency.
Here is how my graph looks like:
And here is how my code looks like:
child: charts.TimeSeriesChart(
series,
animate: true,
domainAxis: new charts.DateTimeAxisSpec(
tickFormatterSpec: new charts.AutoDateTimeTickFormatterSpec(
day: new charts.TimeFormatterSpec(
format: 'dd',
transitionFormat: 'dd MMM',
),
),
),
primaryMeasureAxis: new charts.NumericAxisSpec(
renderSpec: new charts.GridlineRendererSpec(
// Tick and Label styling here.
labelStyle: new charts.TextStyleSpec(
fontSize: 10, // size in Pts.
color: charts.MaterialPalette.black
),
)
),
defaultRenderer: charts.LineRendererConfig(
includeArea: true,
includeLine: true,
includePoints: true,
strokeWidthPx: 0.5,
radiusPx: 1.5
),
dateTimeFactory: const charts.LocalDateTimeFactory(),
behaviors: [
charts.PanAndZoomBehavior(),
charts.SelectNearest(
eventTrigger: charts.SelectionTrigger.tap
),
charts.LinePointHighlighter(
symbolRenderer: CustomCircleSymbolRenderer(size: size),
),
],
selectionModels: [
charts.SelectionModelConfig(
type: charts.SelectionModelType.info,
changedListener: (charts.SelectionModel model) {
if(model.hasDatumSelection) {
final tankVolumeValue = model.selectedSeries[0].measureFn(model.selectedDatum[0].index).round();
final dateValue = model.selectedSeries[0].domainFn(model.selectedDatum[0].index);
CustomCircleSymbolRenderer.value = '$dateValue \n $tankVolumeValue L';
}
})
]),
),
);
Any idea on how to change the label is welcome.

With charts_flutter you can specify a NumberFormat using their BasicNumericTickFormatterSpec class (which... doesn't seem basic at all).
Then supply this formatter class to your chart
Below I've used NumberFormat.compact() which would turn 60,000 into 60K.
/// Formatter for Y-axis numbers using [NumberFormat] compact
///
/// Used in the [NumericAxisSpec] below.
final myNumericFormatter =
BasicNumericTickFormatterSpec.fromNumberFormat(
NumberFormat.compact() // ← your format goes here
);
return TimeSeriesChart(seriesList,
animate: animate,
// Use myNumericFormatter on the primaryMeasureAxis
primaryMeasureAxis: NumericAxisSpec(
tickFormatterSpec: myNumericFormatter // ← pass your formatter here
),
Here's a full running example using the above:
import 'package:charts_flutter/flutter.dart';
import 'package:flutter/material.dart';
import 'package:intl/intl.dart';
class ChartFormatPage extends StatelessWidget {
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text('Chart Format'),
),
body: Center(
child: ChartCustomYAxis.withSampleData(),
)
);
}
}
class ChartCustomYAxis extends StatelessWidget {
final List<Series> seriesList;
final bool animate;
ChartCustomYAxis(this.seriesList, {this.animate});
/// Creates a [TimeSeriesChart] with sample data and no transition.
factory ChartCustomYAxis.withSampleData() {
return ChartCustomYAxis(
_createSampleData(),
// Disable animations for image tests.
animate: false,
);
}
#override
Widget build(BuildContext context) {
/// Formatter for Y-axis numbers using [NumberFormat] compact
///
/// Used in the [NumericAxisSpec] below.
final myNumericFormatter =
BasicNumericTickFormatterSpec.fromNumberFormat(
NumberFormat.compact() // ← your format goes here
);
return TimeSeriesChart(seriesList,
animate: animate,
// Use myNumericFormatter on the primaryMeasureAxis
primaryMeasureAxis: NumericAxisSpec(
tickFormatterSpec: myNumericFormatter // ← pass your formatter here
),
/// Customizes the date tick formatter. It will print the day of month
/// as the default format, but include the month and year if it
/// transitions to a new month.
///
/// minute, hour, day, month, and year are all provided by default and
/// you can override them following this pattern.
domainAxis: DateTimeAxisSpec(
tickFormatterSpec: AutoDateTimeTickFormatterSpec(
day: TimeFormatterSpec(
format: 'd', transitionFormat: 'MM/dd/yyyy'))));
}
/// Create one series with sample hard coded data.
static List<Series<MyRow, DateTime>> _createSampleData() {
final data = [
MyRow(DateTime(2017, 9, 25), 6000),
MyRow(DateTime(2017, 9, 26), 8000),
MyRow(DateTime(2017, 9, 27), 6000),
MyRow(DateTime(2017, 9, 28), 9000),
MyRow(DateTime(2017, 9, 29), 11000),
MyRow(DateTime(2017, 9, 30), 15000),
MyRow(DateTime(2017, 10, 01), 25000),
MyRow(DateTime(2017, 10, 02), 33000),
MyRow(DateTime(2017, 10, 03), 27000),
MyRow(DateTime(2017, 10, 04), 31000),
MyRow(DateTime(2017, 10, 05), 23000),
];
return [
Series<MyRow, DateTime>(
id: 'Cost',
domainFn: (MyRow row, _) => row.timeStamp,
measureFn: (MyRow row, _) => row.cost,
data: data,
)
];
}
}
/// Sample time series data type.
class MyRow {
final DateTime timeStamp;
final int cost;
MyRow(this.timeStamp, this.cost);
}
The above example was stolen from here and modified to show NumberFormat.compact.

Related

How update the domainAxis in charts.DateTimeAxisSpec viewport in flutter_chart?

I have confused with working of flutter_graph. I want to two help yu guys.
I trying to make datetetime charts using charts_flutter package.
I want to make x-axis value 1-2-2018 format instead of oct-2017(this is default style). I want to update all x-values tp dd-MM-YYY style. How to do that,.
2)I want to make update domainAxis in charts.DateTimeAxisSpec viewport. How to update start and end properity in correct format? i actually iam using API value. so its not static, its dynamic, its changes all time. so how to update viewport in properly.
I am stucking in this two things. here i am sharing the model one code. Please add your things.
class LineChart extends StatefulWidget {
final List<LineChartModel> firstGraph;
const LineChart({
Key? key,
required this.firstGraph,
}) : super(key: key);
#override
State<LineChart> createState() => _LineChartState();
}
class _LineChartState extends State<LineChart> {
//late AnalyticsNotifier noti;
#override
void initState() {
super.initState();
}
#override
Widget build(BuildContext context) {
List<charts.Series<LineChartModel, DateTime>> series = [
charts.Series<LineChartModel, DateTime>(
id: 'Graph1',
colorFn: (_, __) => charts.MaterialPalette.deepOrange.shadeDefault,
domainFn: (LineChartModel sales, _) => sales.date,
measureFn: (LineChartModel sales, _) => sales.count,
data: widget.firstGraph,
),
];
return Column(
crossAxisAlignment: CrossAxisAlignment.start,
children: [
Expanded(
child: charts.TimeSeriesChart(
series,
animate: true,
behaviors: [
charts.SlidingViewport(),
charts.PanAndZoomBehavior(),
charts.ChartTitle('Day',
behaviorPosition: charts.BehaviorPosition.bottom,
titleStyleSpec: const charts.TextStyleSpec(fontSize: 15),
titleOutsideJustification:
charts.OutsideJustification.middleDrawArea),
charts.ChartTitle('Count of observations',
behaviorPosition: charts.BehaviorPosition.start,
titleStyleSpec: const charts.TextStyleSpec(fontSize: 15),
titleOutsideJustification:
charts.OutsideJustification.middleDrawArea),
],
dateTimeFactory: const charts.LocalDateTimeFactory(),
domainAxis: charts.DateTimeAxisSpec(//how to add this one in proper.
viewport: charts.DateTimeExtents(
start: widget.firstGraph.first.date,
end: widget.firstGraph[5].date,
),
renderSpec: const charts.SmallTickRendererSpec(
labelCollisionOffsetFromAxisPx: 35,
labelCollisionRotation: -80,
// Tick and Label styling here.
labelStyle: charts.TextStyleSpec(
fontSize: 12, // size in Pts.
fontFamily: 'Montserrat',
color: charts.MaterialPalette.black,
),
)),
primaryMeasureAxis: const charts.NumericAxisSpec(
//viewport: charts.NumericExtents(0, 10),
renderSpec: charts.GridlineRendererSpec(
// Tick and Label styling here.
labelStyle: charts.TextStyleSpec(
fontSize: 9, // size in Pts.
fontFamily: 'Montserrat',
color: charts.MaterialPalette.black,
),
),
),
defaultRenderer: charts.LineRendererConfig(
includeArea: true,
includeLine: true,
areaOpacity: 0.25,
includePoints: true,
layoutPaintOrder: 1,
radiusPx: 3,
roundEndCaps: false,
strokeWidthPx: 1,
),
),
)
],
);
}
}
class LineChartModel {
final DateTime date;
final int count;
LineChartModel(
this.date,
this.count,
);
}

flutter charts timeseries bar chart with x axis time as label

i'm using charts_flutter: ^0.12.0 to implement bar chart with fixed time like 6,8,10,12,14,16,18,22 hours of the day in x axis, but with no success, tried the example but i get only two label's on the x axis 6 and 18 corresponding to the data, kindly help me with implementing the same. Trying to achieve as shown in the pic
The code sample i have tried is
class ChartsDaily extends StatelessWidget {
List<charts.Series<dynamic, DateTime>> seriesList = _createSampleData();
bool animate = false;
//ChartsDaily(this.seriesList, {this.animate = false});
ChartsDaily({Key? key}) : super(key: key);
/// Creates a [TimeSeriesChart] with sample data and no transition.
factory ChartsDaily.withSampleData() {
return ChartsDaily();
}
#override
Widget build(BuildContext context) {
return charts.TimeSeriesChart(
seriesList,
defaultRenderer: charts.BarRendererConfig<DateTime>(
barRendererDecorator:
charts.BarLabelDecorator<DateTime>() // charts.BarLabelDecorator
),
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(),
domainAxis: charts.DateTimeAxisSpec(
tickProviderSpec: charts.DayTickProviderSpec(increments: [1]),
tickFormatterSpec: charts.AutoDateTimeTickFormatterSpec(
day: charts.TimeFormatterSpec(
format: 'HH:mm', transitionFormat: 'HH:mm')),
),
secondaryMeasureAxis: charts.NumericAxisSpec(
renderSpec: charts.GridlineRendererSpec(
lineStyle: charts.LineStyleSpec(
dashPattern: [4, 4],
color: charts.ColorUtil.fromDartColor(Colors.grey.shade300))),
tickProviderSpec: charts.BasicNumericTickProviderSpec(
desiredMinTickCount: 5,
desiredTickCount: 5,
dataIsInWholeNumbers: true,
zeroBound: true,
)),
// domainAxis: charts.DateTimeAxisSpec(
// tickProviderSpec: charts.DateTimeEndPointsTickProviderSpec(),
// tickFormatterSpec: charts.AutoDateTimeTickFormatterSpec(
// day: charts.TimeFormatterSpec(
// format: 'HH:mm', transitionFormat: 'HH:mm', noonFormat: 'HH:mm'),
// // hour: charts.TimeFormatterSpec(format: 'Hm', transitionFormat: 'Hm'),
// ),
// showAxisLine: false,
// viewport: charts.DateTimeExtents(
// start: DateTime(2022, 05, 04, 06), end: DateTime(2022, 05, 04, 22)),
// ),
);
}
/// Create one series with sample hard coded data.
static List<charts.Series<TimeSeriesSales, DateTime>> _createSampleData() {
final data = [
TimeSeriesSales(DateTime(2022, 5, 4, 6, 0), 5),
TimeSeriesSales(DateTime(2022, 5, 4, 10, 30), 25),
TimeSeriesSales(DateTime(2022, 5, 4, 14, 0), 100),
TimeSeriesSales(DateTime(2022, 5, 4, 18, 0), 75),
];
return [
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);
}
Also need to have y axis values not starting from 0. TIA
I think you need the StaticNumericTickProviderSpec for the domainAxis of your chart.
This is the example from Google. I hope it can help you

How to make a flutter chart line chart?

this is my current graph look's like but i want to make tickProviderSpec as the average line
This is what i have done. Is that possible to make a white line at the Center of line chart. Currently, Im using StaticNumericTickProviderSpec to draw the average line. I only need one average line in my line chart. Any idea to do this?
import 'package:charts_flutter/flutter.dart';
import 'package:flutter/cupertino.dart';
import 'package:charts_flutter/flutter.dart' as charts;
class WeightTracker_time_series_chart extends StatelessWidget {
final List<charts.Series> seriesList;
final bool animate;
WeightTracker_time_series_chart(this.seriesList, {this.animate});
factory WeightTracker_time_series_chart.withSampleData() {
return new WeightTracker_time_series_chart(
_createSampleData(),
animate: false,
);
}
List getdata =["1","2","3"];
#override
Widget build(BuildContext context) {
return new charts.LineChart(seriesList,
animate: animate,
defaultRenderer: new charts.LineRendererConfig( includeArea: true,
includePoints: true,
includeLine: true,
stacked: true,),
layoutConfig: charts.LayoutConfig(
leftMarginSpec: charts.MarginSpec.fixedPixel(60),
topMarginSpec: charts.MarginSpec.fixedPixel(10),
rightMarginSpec: charts.MarginSpec.fixedPixel(0),
bottomMarginSpec: charts.MarginSpec.fixedPixel(20)
),
flipVerticalAxis: false,
defaultInteractions: false,
behaviors: [new charts.PanAndZoomBehavior()],
domainAxis: new charts.NumericAxisSpec(
viewport: new charts.NumericExtents(20, 120),
renderSpec: charts.GridlineRendererSpec(
lineStyle: charts.LineStyleSpec(
color: charts.MaterialPalette.white,
thickness: 1,
)
),
tickProviderSpec: new charts.StaticNumericTickProviderSpec(
// Create the ticks to be used the domain axis.
_createTickSpec(),
)),
selectionModels: [
new charts.SelectionModelConfig(
changedListener: (SelectionModel model) {
print( model.selectedSeries[0].measureFn(
model.selectedDatum[0].index));
}
)
],
primaryMeasureAxis: new charts.NumericAxisSpec(
renderSpec:
charts.GridlineRendererSpec(
labelOffsetFromAxisPx: 20,
labelAnchor: charts.TickLabelAnchor.before,
lineStyle: charts.LineStyleSpec(
color: charts.MaterialPalette.white,
thickness: 2,
)
),
tickProviderSpec: new charts.StaticNumericTickProviderSpec(
// Create the ticks to be used the domain axis.
<charts.TickSpec<num>>[
new charts.TickSpec(50, label: '80 ', style: charts.TextStyleSpec(fontSize: 14)),
],
)
),
}
List<charts.TickSpec<num>> _createTickSpec() {
List<charts.TickSpec<num>> _tickProvidSpecs = new List<charts.TickSpec<num>>();
double d = 0;
double day= 0;
for(int i = 0; i< getdata.length ; i++) {
_tickProvidSpecs.add(new charts.TickSpec(d,label: '$day%', style: charts.TextStyleSpec(fontSize: 14)));
d +=20;
day+=1;
}
return _tickProvidSpecs;
}
static List<charts.Series<day_kg, int>> _createSampleData() {
final myFakeDesktopData = [
new day_kg(0, 70),
new day_kg(20, 85),
new day_kg(40, 80),
];
return [
new charts.Series<day_kg, int>(
id: 'weight',
fillColorFn: (_, __) => charts.MaterialPalette.white,
colorFn: (_, __) => charts.MaterialPalette.red.shadeDefault,
domainFn: (day_kg data, _) => data.date,
measureFn: (day_kg data, _) => data.kg,
domainLowerBoundFn: (day_kg data, _) => data.domainLower,
measureLowerBoundFn: (day_kg data, _) => data.measureLower,
strokeWidthPxFn: (_, __) => 4,
data: myFakeDesktopData,
),
];
}
}
class day_kg {
final int date;
final int kg;
final int domainUpper = 100;
final int domainLower = 0;
final int measureUpper = 100;
final int measureLower = 0;
day_kg(this.date, this.kg);
}

Set minimum and maximum range of axes in charts_flutter

How can I set the range in x axis in charts_flutter? My data sample is like (5000, 5.0),(5001, 25.2),(5002, 100.5),(5003, 75.8).
My code is
/// Example of a simple line chart.
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:flutter/material.dart';
class SimpleLineChart extends StatelessWidget {
final List<charts.Series> seriesList;
final bool animate;
SimpleLineChart(this.seriesList, {this.animate});
/// Creates a [LineChart] with sample data and no transition.
factory SimpleLineChart.withSampleData() {
return SimpleLineChart(
_createSampleData(),
// Disable animations for image tests.
animate: false,
);
}
#override
Widget build(BuildContext context) {
return Container(
height: 300,
// decoration: const BoxDecoration(color: Color(0xff232d37)),
width: double.infinity,
padding:
const EdgeInsets.only(right: 18.0, left: 12.0, top: 24, bottom: 12),
child: charts.LineChart(seriesList, animate: animate),
);
}
/// Create one series with sample hard coded data.
static List<charts.Series<LinearSales, int>> _createSampleData() {
final data = [
LinearSales(5000, 5.0),
LinearSales(5001, 25.2),
LinearSales(5002, 100.5),
LinearSales(5003, 75.8),
];
return [
charts.Series<LinearSales, int>(
id: 'Sales',
colorFn: (_, __) => charts.MaterialPalette.blue.shadeDefault,
domainFn: (LinearSales sales, _) {
return sales.year;
},
measureFn: (LinearSales sales, _) {
return sales.sales;
},
data: data,
domainLowerBoundFn: (s, _) => 5000,
domainUpperBoundFn: (s, _) => 5010,
)
];
}
}
/// Sample linear data type.
class LinearSales {
final int year;
final double sales;
LinearSales(this.year, this.sales);
}
The charts looks like
It shows a straight line but I want x axis to start at 5000 and end on 5010. I tried setting it in
domainLowerBoundFn and domainUpperBoundFn but it still starts at 0. How do I fix it?
Ref: Charts Flutter Gallery
You can set domainAxis.
How about this?
child: charts.LineChart(
seriesList,
animate: animate,
domainAxis: const charts.NumericAxisSpec(
tickProviderSpec:
charts.BasicNumericTickProviderSpec(zeroBound: false),
viewport: charts.NumericExtents(5000.0, 5005.0),
),
),
or this?
child: charts.LineChart(
seriesList,
animate: animate,
domainAxis: const charts.NumericAxisSpec(
tickProviderSpec:
charts.BasicNumericTickProviderSpec(zeroBound: false),
),
),
You can use the next code for Y-axis:
primaryMeasureAxis: charts.NumericAxisSpec(
tickProviderSpec:
charts.BasicNumericTickProviderSpec(desiredTickCount: 3)),
Full example looks like:
ScatterPlotChart(
[seriesDistorted],
animate: true,
domainAxis: const NumericAxisSpec(
tickProviderSpec: BasicNumericTickProviderSpec(
// Vertical axis every 2 ticks from 0 to 10
dataIsInWholeNumbers: true,
zeroBound: false,
desiredTickCount: 6),
),
primaryMeasureAxis: const NumericAxisSpec(
tickProviderSpec: BasicNumericTickProviderSpec(desiredTickCount: 6)),
);

How to add a name to a chart on flutter, x- and y-axis?

I have been working with the online gallery of Flutter charts (https://google.github.io/charts/flutter/gallery.html) but I'm struggling to add a title for x & y axis values.
Can somebody help me or tell me how to add the labels to the graph?
Its possible using behaviors property, check the code
var chart = charts.LineChart(seriesList,
behaviors: [
new charts.ChartTitle('Dimension',
behaviorPosition: charts.BehaviorPosition.bottom,
titleStyleSpec: chartsCommon.TextStyleSpec(fontSize: 11),
titleOutsideJustification:
charts.OutsideJustification.middleDrawArea),
new charts.ChartTitle('Dose, mg',
behaviorPosition: charts.BehaviorPosition.start,
titleStyleSpec: chartsCommon.TextStyleSpec(fontSize: 11),
titleOutsideJustification:
charts.OutsideJustification.middleDrawArea)
],
defaultRenderer: new charts.LineRendererConfig(includePoints: true));
Source https://google.github.io/charts/flutter/example/behaviors/chart_title
use the 'behavior' list for set title of chart
Widget build(BuildContext context) {
return new charts.LineChart(
seriesList,
animate: animate,
behaviors: [
new charts.ChartTitle('Top title text',
subTitle: 'Top sub-title text',
behaviorPosition: charts.BehaviorPosition.top,
titleOutsideJustification: charts.OutsideJustification.start,
innerPadding: 18),
new charts.ChartTitle('Bottom title text',
behaviorPosition: charts.BehaviorPosition.bottom,
titleOutsideJustification:
charts.OutsideJustification.middleDrawArea),
new charts.ChartTitle('Start title',
behaviorPosition: charts.BehaviorPosition.start,
titleOutsideJustification:
charts.OutsideJustification.middleDrawArea),
new charts.ChartTitle('End title',
behaviorPosition: charts.BehaviorPosition.end,
titleOutsideJustification:
charts.OutsideJustification.middleDrawArea),
],
);
}
You can do it by using behaviors using line annotations iterating your list data and make a new LineAnnotationSegment array but you should be aware that some titles may overlap when the next time point is very close.
final data = [
LinearPrices(DateTime(2020, 9, 19), 5),
LinearPrices(DateTime(2020, 9, 26), 15),
LinearPrices(DateTime(2020, 10, 3), 20),
LinearPrices(DateTime(2020, 10, 10), 17),
];
#override
Widget build(BuildContext context) {
return charts.TimeSeriesChart(seriesList, animate: false, behaviors: [
charts.RangeAnnotation( data.map((e) => charts.LineAnnotationSegment(
e.timestamp, charts.RangeAnnotationAxisType.domain,
middleLabel: '\$${e.price}')).toList()),
]);
}
Nevertheless you can use a callback to paint when the user clicks the line by painting either a custom text at the bottom or as a custom label using behaviors like this:
import 'package:flutter/material.dart';
import 'package:charts_flutter/flutter.dart' as charts;
import 'package:intl/intl.dart';
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
Widget build(BuildContext context) {
final data = [
LinearPrices(DateTime(2020, 9, 19), 5),
LinearPrices(DateTime(2020, 9, 26), 15),
LinearPrices(DateTime(2020, 10, 3), 20),
LinearPrices(DateTime(2020, 10, 10), 17),
];
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: Text('Chart'),
),
body: ChartPricesItem(data),
));
}
}
class ChartPricesItem extends StatefulWidget {
final List<LinearPrices> data;
ChartPricesItem(this.data);
static List<charts.Series<LinearPrices, DateTime>> _createSeries(
List<LinearPrices> data) {
return [
charts.Series<LinearPrices, DateTime>(
id: 'Prices',
colorFn: (_, __) => charts.MaterialPalette.deepOrange.shadeDefault,
domainFn: (LinearPrices sales, _) => sales.timestamp,
measureFn: (LinearPrices sales, _) => sales.price,
data: data,
)
];
}
#override
_ChartPricesItemState createState() => _ChartPricesItemState();
}
class _ChartPricesItemState extends State<ChartPricesItem> {
DateTime _time;
double _price;
// Listens to the underlying selection changes, and updates the information relevant
void _onSelectionChanged(charts.SelectionModel model) {
final selectedDatum = model.selectedDatum;
DateTime time;
double price;
// We get the model that updated with a list of [SeriesDatum] which is
// simply a pair of series & datum.
if (selectedDatum.isNotEmpty) {
time = selectedDatum.first.datum.timestamp;
price = selectedDatum.first.datum.price;
}
// Request a build.
setState(() {
_time = time;
_price = price;
});
}
#override
Widget build(BuildContext context) {
final simpleCurrencyFormatter =
charts.BasicNumericTickFormatterSpec.fromNumberFormat(
NumberFormat.compactSimpleCurrency());
var behaviors;
// Check if the user click over the line.
if (_time != null && _price != null) {
behaviors = [
charts.RangeAnnotation([
charts.LineAnnotationSegment(
_time,
charts.RangeAnnotationAxisType.domain,
labelDirection: charts.AnnotationLabelDirection.horizontal,
labelPosition: charts.AnnotationLabelPosition.margin,
labelStyleSpec:
charts.TextStyleSpec(fontWeight: FontWeight.bold.toString()),
middleLabel: '\$$_price',
),
]),
];
}
var chart = charts.TimeSeriesChart(
ChartPricesItem._createSeries(widget.data),
animate: false,
// Include timeline points in line
defaultRenderer: charts.LineRendererConfig(includePoints: true),
selectionModels: [
charts.SelectionModelConfig(
type: charts.SelectionModelType.info,
changedListener: _onSelectionChanged,
)
],
// This is the part where you paint label when you click over the line.
behaviors: behaviors,
// Sets up a currency formatter for the measure axis.
primaryMeasureAxis: charts.NumericAxisSpec(
tickFormatterSpec: simpleCurrencyFormatter,
tickProviderSpec:
charts.BasicNumericTickProviderSpec(zeroBound: false)),
/// Customizes the date tick formatter. It will print the day of month
/// as the default format, but include the month and year if it
/// transitions to a new month.
///
/// minute, hour, day, month, and year are all provided by default and
/// you can override them following this pattern.
domainAxis: charts.DateTimeAxisSpec(
tickFormatterSpec: charts.AutoDateTimeTickFormatterSpec(
day: charts.TimeFormatterSpec(
format: 'd', transitionFormat: 'dd/MM/yyyy'),
minute: charts.TimeFormatterSpec(
format: 'mm', transitionFormat: 'dd/MM/yyyy HH:mm'))),
);
var chartWidget = Padding(
padding: EdgeInsets.all(16),
child: SizedBox(
height: 200.0,
child: chart,
),
);
final children = <Widget>[chartWidget];
// If there is a selection, then include the details.
if (_time != null) {
children.add(Padding(
padding: EdgeInsets.only(top: 4.0),
child: Text(DateFormat('dd/MM/yyyy hh:mm').format(_time),
style: Theme.of(context).textTheme.bodyText1)));
}
return SingleChildScrollView(
child: Column(
children: <Widget>[
const SizedBox(height: 8),
Text("Product Prices", style: Theme.of(context).textTheme.headline5),
Column(children: children),
],
),
);
}
}
/// Sample linear data type.
class LinearPrices {
final DateTime timestamp;
final double price;
LinearPrices(this.timestamp, this.price);
}
This is the result: