How to add a logarithmic axis scale in the Flutter radial gauge (SfRadialGauge)
Description
This article describes how to add a logarithmic axis in Flutter radial gauge.
Solution
You can create a logarithmic axis in radial gauge widget by extending a custom axis renderer class from radial axis renderer class.
Step 1: Create a custom axis renderer class by extending it from radial axis renderer.
class _CustomAxisRenderer extends RadialAxisRenderer { _CustomAxisRenderer() : super(); }
Step 2: The text value of the labels can be changed a required logarithmic visible labels by overriding the generateVisibleLabels method of custom axis renderer.
@override List<CircularAxisLabel> generateVisibleLabels() { final List<CircularAxisLabel> _visibleLabels = <CircularAxisLabel>[]; num _minimum = _logBase(minimum, 10); num _maximum = _logBase(maximum, 10); for (num i = _minimum; i <= _maximum; i++) { final int _value = math.pow(10, i).floor(); // logBase value is 10 final CircularAxisLabel label = CircularAxisLabel( axisLabelStyle, _value.toInt().toString(), i, false); label.value = _value; _visibleLabels.add(label); } _labelsCount = _visibleLabels.length; return _visibleLabels; }
// To convert the log value into linear value num _logBase(num value, num base) => math.log(value) / math.log(base);
Step 3: To find the factor values based on the respective logarithmic value, override the valueToFactor method of custom axis renderer and implement the logics for converting the values.
@override double valueToFactor(double value) { double _number = _logBase(value, 10) / (_labelsCount - 1); return _number; }
Step 4: Create the radial gauge and add the custom axis in it by customizing the axis range as desired.
@override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, body: Center( child: SfRadialGauge( axes: <RadialAxis>[ CustomAxis( minimum: 1, maximum: 10000, ) ], ), ), ); }
Step 5: Return the custom axis renderer in the onCreateAxisRenderer event of radial axis.
@override Widget build(BuildContext context) { return Scaffold( backgroundColor: Colors.white, body: Center( child: SfRadialGauge( axes: <RadialAxis>[ CustomAxis( minimum: 1, maximum: 10000, onCreateAxisRenderer: () { final _CustomAxisRenderer renderer = _CustomAxisRenderer(); return renderer; }, ) ], ), ), ); }
Step 6: Include the needle pointer to annotate the desired value.
pointers: <GaugePointer>[NeedlePointer(value: 1000)]
Output
You can download the sample from this link.