toImage method

Future<Image?> toImage({
  1. double pixelRatio = 1.0,
})

Method to convert the SfCartesianChart as an image.

As this method is in the widget’s state class, you have to use a global key to access the state to call this method. Returns the dart:ui.image

final GlobalKey<SfCartesianChartState> _key = GlobalKey();
@override
Widget build(BuildContext context) {
 return Scaffold(
   body: Column(
     children: [SfCartesianChart(
       key: _key
         series: <CartesianSeries<SalesData, num>>[
               AreaSeries<SalesData, num>(
                   dataSource: chartData,
               ),
             ],
       ),
             RaisedButton(
               child: Text(
                 'To Image',
               ),
              onPressed: _renderImage,
               shape: RoundedRectangleBorder(
                   borderRadius: BorderRadius.circular(20)),
             )
     ],
   ),
 );
}
Future<void> _renderImage() async {
 dart_ui.Image data = await _key.currentState.toImage(pixelRatio: 3.0);
 final bytes = await data.toByteData(format: dart_ui.ImageByteFormat.png);
 if (data != null) {
   await Navigator.of(context).push(
     MaterialPageRoute(
       builder: (BuildContext context) {
         return Scaffold(
           appBar: AppBar(),
           body: Center(
             child: Container(
               color: Colors.white,
               child: Image.memory(bytes.buffer.asUint8List()),
           ),
          ),
        );
       },
     ),
   );
 }
}

Implementation

/// Future<void> _renderImage() async {
///  dart_ui.Image data = await _key.currentState.toImage(pixelRatio: 3.0);
///  final bytes = await data.toByteData(format: dart_ui.ImageByteFormat.png);
///  if (data != null) {
///    await Navigator.of(context).push(
///      MaterialPageRoute(
///        builder: (BuildContext context) {
///          return Scaffold(
///            appBar: AppBar(),
///            body: Center(
///              child: Container(
///                color: Colors.white,
///                child: Image.memory(bytes.buffer.asUint8List()),
///            ),
///           ),
///         );
///        },
///      ),
///    );
///  }
/// }
/// ```
Future<Image?> toImage({double pixelRatio = 1.0}) async {
  final RenderRepaintBoundary? boundary =
      context.findRenderObject() as RenderRepaintBoundary?;
  if (boundary != null) {
    final Image image = await boundary.toImage(pixelRatio: pixelRatio);
    return image;
  }

  return null;
}